how to send email using Persits.MailSender - asp-classic

i want to send email using Persits.MailSender object. i found one solution and i include this code this solution works and Object created:
<%
posted = request.form ("submit")
if posted = "Submit" then
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'' Customize the following 5 lines with your own information. ''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
vtoaddress = "_____" ' Change this to the email address you will be receiving your notices.
vmailhost = Application("ServerAddress") ' Change this to your actual Domain name.
vfromaddress = "_____" ' Change this to the email address you will use to send and authenticate with.
vfrompwd = "_______________" ' Change this to the above email addresses password.
vsubject = "ASP Contact Form" 'Change this to your own email message subject.
'''''''''''''''''''''''''''''''''''''''''''
'' DO NOT CHANGE ANYTHING PAST THIS LINE ''
'''''''''''''''''''''''''''''''''''''''''''
vfromname = request.form ("TName")
vbody = request.form ("TBody")
vrplyto = request.form ("TEmail")
vmsgbody = vfromname &"<br>"& vrplyto &"<br>"& vbody
Set objEmail = Server.CreateObject("Persits.MailSender")
objEmail.Username = vfromaddress
objEmail.Password = vfrompwd
objEmail.Host = vmailhost
objEmail.From = vfromaddress
objEmail.AddAddress vtoaddress
objEmail.Subject = vsubject
objEmail.Body = vmsgbody
objEmail.IsHTML = True
objEmail.Send
vErr = Err.Description
if vErr <> "" then
response.write vErr & "<br><br>There was an error on this page."
else
response.write "Thank you, your message has been sent."
End If
Set objEmail = Nothing
response.write "Thank you, your message has been sent."
end if
%>
<html><body>
<form name="SendEmail01" method="post">
<table border=0>
<tr>
<td>Name:</td>
<td><input type="text" name="TName" size="30"></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" name="TEmail" size="30"></td>
</tr>
<tr>
<td>Body:</td>
<td><textarea rows="4" name="TBody" cols="30"></textarea></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit"></td>
</tr>
</form>
</body></html>
after filling all fields and submitting page then error occured like:
Persits.MailSender.4 error '800a0004'
Cannot assign requested address.
/contact_form.asp, line 34
please help me..

I hope so this piece of code will help you
<%
Class HVMailer
Private mMail
Private Sub Class_Initialize()
Set mMail = Server.CreateObject("Persits.MailSender")
mMail.Host = ""
mMail.Username = ""
mMail.Password = ""
mMail.TLS = True
End Sub
Public Property Let FromAddress(sFrom)
mMail.From = trim(sFrom)
End Property
Public Property Let FromName(sFromName)
mMail.FromName = trim(sFromName)
End Property
Public Property Let ReplyTo(sReply)
mMail.AddReplyTo trim(sReply), trim(sReply)
End Property
Public Property Let Subject(sSubject)
mMail.Subject = sSubject
End Property
Public Property Let BodyText(sBodyText)
mMail.Body = sBodyText
End Property
Public Property Let HTML(bHTML)
mMail.isHTML = bHTML
End Property
Public Sub AddRecipient(sAddress, sName)
sAddress = trim(sAddress)
if mMail.ValidateAddress(sAddress)= 0 Then
mMail.AddAddress sAddress, sName
end if
End Sub
Public Sub AddCC(sAddress, sName)
sAddress = trim(sAddress)
if mMail.ValidateAddress(sAddress)= 0 Then
mMail.AddCC sAddress, sName
end if
End Sub
Public Sub AddBCC(sAddress, sName)
sAddress = trim(sAddress)
if mMail.ValidateAddress(sAddress)= 0 Then
mMail.AddBCC sAddress, sName
end if
End Sub
Public Sub AddAttachment(sFile)
mMail.AddAttachment sFile
End Sub
Public function Send()
On Error Resume Next
mReturn = True
mMail.Send
if Err<>0 Then
mReturn = false
end if
Set mMail = Nothing
send = mReturn
End Function
End Class
%>

Related

How to pass value parameter in url that cannot excecute directly in url?

So i have this program that sending notification value to other page and show the notification, but the problem is you can edit the value in the url,
If lngErrNo <> 0 Then
response.write "Error while update Product."
response.end
Else
v_strMsg = "Edit Kelipatan Jumlah Pesanan Berhasil!"
Response.Redirect "global_notification.asp?strMsg=" & v_strMsg
End If
the problem is you can edit v_strMsg in url for the example abc.com/global_notification.asp?strMsg= "anything you can edit the value here", and the display page is look like this
<body>
<table class="1" width=70% cellpadding="0" cellspacing="0">
<tr>
<td colspan="3" background="images/bgtable.gif"><div align="left" class="fontwhiteheader13">
ATTENTION!!</div>
</td>
</tr>
<tr>
<td valign="top"><table width=100% height="360" cellpadding="2" cellspacing="2" bgcolor="white">
<tr>
<td align=center class="fontblueheader13"><%=Request.QueryString("strMsg")%>
</td>
</tr>
</table></td></tr></table>
</body>
any possible way to sending the value without changing it to POST metod? i try htmlEncode but v_strMsg still can be edited in url, any suggestion?
You need a signed URL.
A signed URL includes a digital signature that proves the request was generated by the server.
The first thing you need to do is create a secret key:
' Generate your own key from:
' https://www.allkeysgenerator.com/Random/Security-Encryption-Key-Generator.aspx
Const secret_key = "G+KbPeShVmYq3s6v9y$B&E)H#McQfTjW"
In this example it's a 256 bit key.
You also need a hashing function:
hash.asp
<%
' Might as well store the secret key constant in this file:
Const secret_key = "G+KbPeShVmYq3s6v9y$B&E)H#McQfTjW"
Function Hash(ByVal Input, HashAlgorithm)
' Select the System.Security.Cryptography value.
Select Case uCase(HashAlgorithm)
Case "MD5"
HashAlgorithm = "MD5CryptoServiceProvider"
Case "SHA1"
HashAlgorithm = "SHA1CryptoServiceProvider"
Case "SHA2","SHA256"
HashAlgorithm = "SHA256Managed"
Case "SHA384"
HashAlgorithm = "SHA384Managed"
Case "SHA5","SHA512"
HashAlgorithm = "SHA512Managed"
Case Else
HashAlgorithm = "SHA1CryptoServiceProvider"
End Select
' Convert the input to bytes if not already.
If NOT VarType(Input) = 8209 Then
Dim utf8 : Set utf8 = Server.CreateObject("System.Text.UTF8Encoding")
Input = utf8.GetBytes_4(Input)
Set utf8 = Nothing
End If
' Perform the hash.
Dim hAlg : Set hAlg = Server.CreateObject("System.Security.Cryptography." & HashAlgorithm)
Dim hEnc : Set hEnc = Server.CreateObject("MSXML2.DomDocument").CreateElement("encode")
hEnc.dataType = "bin.hex"
hEnc.nodeTypedValue = hAlg.ComputeHash_2((Input))
Hash = hEnc.Text
Set hEnc = Nothing
Set hAlg = Nothing
End Function
%>
Now you're ready to sign your URL with a digital signature.
' Be sure to include "hash.asp"
' Your message:
v_strMsg = "Edit Kelipatan Jumlah Pesanan Berhasil!"
' A unix timestamp:
v_uts = DateDiff("s","1970-01-01 00:00:00",Now())
' NOTE: Your servers timezone should be set to UTC to generate a true unix timestamp,
' but it doesn't really matter, as long as "global_notification.asp" is on the same
' server, or a server set to the same timezone as the page you're generating the
' signature from.
' Now we create the signature as so:
v_signature = Hash(v_strMsg & v_uts & secret_key,"SHA256")
' Finally, redirect to "global_notification.asp"
Response.Redirect "global_notification.asp?strMsg=" & Server.URLEncode(v_strMsg) & "&ts=" & v_uts & "&signature=" & v_signature
Example redirect:
global_notification.asp?strMsg=Edit+Kelipatan+Jumlah+Pesanan+Berhasil%21&ts=1612794802&signature=61016c0a0460902cc4a19f092dcbb4fd818aa9c88d2631e087868253e73983da
Now to validate the signature on global_notification.asp:
<!--#include file = "hash.asp" -->
<%
Dim v_strMsg, v_uts, v_signature, v_uts_now
v_strMsg = Request.QueryString("strMsg")
v_uts = Request.QueryString("ts")
v_signature = Request.QueryString("signature")
' Do some basic validation first.
If v_signature = "" Then
Response.Write "Missing Signature"
Response.End()
ElseIf v_uts = "" Then
Response.Write "Missing Timestamp"
Response.End()
ElseIf NOT Len(v_signature) = 64 Then
Response.Write "Invalid Signature"
Response.End()
ElseIf NOT (IsNumeric(v_uts) AND Len(v_uts) = 10) Then
Response.Write "Invalid Timestamp"
Response.End()
End If
' Validate the signature. To do this, we simply recreate what we're expecting the signature
' to be, and compare it to the one being passed.
If NOT Hash(v_strMsg & v_uts & secret_key,"SHA256") = v_signature Then
Response.Write "Invalid Signature"
Response.End()
End If
' Now let's set an expiration period for the link, say 30 seconds? (or 86400 seconds for a day, 604800 for a week etc).
v_uts = Int(v_uts) + 30
v_uts_now = DateDiff("s","1970-01-01 00:00:00",Now())
If v_uts_now >= v_uts Then
Response.Write "Expired Link"
Response.End()
End If
' At this point, everything is good.
' Go ahead and display the message:
%>
<body>
<table class="1" width="70%" cellpadding="0" cellspacing="0">
<tr>
<td colspan="3" background="images/bgtable.gif"><div align="left" class="fontwhiteheader13"> ATTENTION!!</div></td>
</tr>
<tr>
<td valign="top"><table width="100%" height="360" cellpadding="2" cellspacing="2" bgcolor="white">
<tr>
<td align=center class="fontblueheader13"><%=v_strMsg%></td>
</tr>
</table></td>
</tr>
</table>
</body>
Now if you try and change the message (or the timestamp) you'll get an Invalid Signature error. The only way to generate a valid working link is to know the secret key, which of course is hidden.

Site redirects to login page in Chrome but not IE?

I am working on various bug fixes on a small website and one thing is really confusing me.
Is there an easy explanation as to why some pages will redirect to a login page instead of the actual destination... but only while using Chrome?
Example: This page is supposed to check input against our mailing list and either add the details or return a message saying they're already on the list. It works fine in IE (go figure) but when I try it in Chrome it redirects me to the account login page.
HTML:
<%# Page Language="VB" MasterPageFile="~/Standard-no-menu.master" AutoEventWireup="false" CodeFile="join-email.aspx.vb" Inherits="JoinEmail" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
<style type="text/css"><!-- #import url("/update-details.css"); --></style>
<script type="text/javascript" language="javascript" src="js/JScript.js"> </script>
<script language="javascript" type="text/javascript">
function validateForm()
{
if (aForgotPwd.style.display != null && aForgotPwd.style.display.toString() != "none") {
var emailEle = document.getElementById("<%= txtEmail.ClientID %>");
emailEle.focus();
return false;
}
if(document.getElementById('<%= txtEmail.ClientID %>').value=="")
{
alert("Please enter a value in the field \"Email\".");
document.getElementById('<%= txtEmail.ClientID %>').focus();
return (false);
}
validemail=0;
var checkStr = document.getElementById('<%= txtEmail.ClientID %>').value;
for (i = 0; i < checkStr.length; i++)
{
if(checkStr.charAt(i)=="#")
validemail |= 1;
if(checkStr.charAt(i)==".")
validemail |= 2;
}
if(validemail != 3)
{
alert("Please enter a valid email address.");
document.getElementById('<%= txtEmail.ClientID %>').focus();
return (false);
}
if(document.getElementById('<%= txtFirstName.ClientID %>').value=="")
{
alert("Please enter a value in the field \"First Name\".");
document.getElementById('<%= txtFirstName.ClientID %>').focus();
return (false);
}
if(document.getElementById('<%= txtLastName.ClientID %>').value=="")
{
alert("Please enter a value in the field \"Last Name\".");
document.getElementById('<%= txtLastName.ClientID %>').focus();
return (false);
}
}
</script>
<h1>Join Global PC Mailing List
</h1>
<div class="update-message"><asp:Label ID="lblMessage" runat="Server"></asp:Label></div>
<asp:Panel ID="pnlCreateAccount" runat="server">
<div class="update-row">
<div class="update-mandatory">*</div>
<div class="update-label">Email Address:</div>
<div class="update-field"><asp:TextBox cssClass="textbox" ID="txtEmail" MaxLength="255" width="350" runat="server"></asp:TextBox><b><a id="aForgotPwd" href="/forgotten-password.aspx" style="display:none"> Forgot password?</a></b></div>
</div>
<div class="update-row">
<div class="update-mandatory"> </div>
<div class="update-label"> </div>
<div class="update-field">We will never give your email address to anyone. Read our <a runat="server" href="~/privacy.aspx">privacy policy</a></div>
</div>
<div class="update-row">
<div class="update-mandatory"> </div>
<div class="update-label">Company Name:</div>
<div class="update-field"><asp:TextBox cssClass="textbox" name="txtAccountName" ID="txtAccountName" MaxLength="40" width="350" runat="server"></asp:TextBox>
</div>
</div>
<div class="update-row">
<div class="update-mandatory">*</div>
<div class="update-label">First Name:</div>
<div class="update-field"><asp:TextBox cssClass="textbox" name="txtFirstName" ID="txtFirstName" MaxLength="255" width="350" runat="server"></asp:TextBox></div>
</div>
<div class="update-row">
<div class="update-mandatory">*</div>
<div class="update-label">Last Name:</div>
<div class="update-field"><asp:TextBox cssClass="textbox" name="txtLastName" ID="txtLastName" MaxLength="255" width="350" runat="server"></asp:TextBox></div>
</div>
<h1>Choose Your Email Subscriptions</h1>
<div class="update-row">
<div style="float:left">
<div class="update-mandatory"> </div>
<div class="update-label">Subscribe to General Newsletters:</div>
<div class="update-checkbox"><asp:CheckBox ID="chkGenernalNewsletters" runat="server"></asp:CheckBox></div>
</div>
</div>
<div class="update-row">
<div class="update-mandatory"> </div>
<div class="update-label"> </div>
<div class="update-field">
<div class="green-button">
<asp:LinkButton ID="btnRegister" OnClientClick="return validateForm();" AlternateText="Join Up" Text="Join Up" runat="server" />
</div>
</div>
</div>
</asp:Panel>
</asp:Content>
VB.NET
Imports DataAccessLayer
Imports System.Data
Imports System.Net
Imports System.Net.Mail
Imports com.verticalresponse.api
Partial Class JoinEmail
Inherits System.Web.UI.Page
Dim c As GPCUser
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Master.Page.Title += " | Register"
If TypeOf Session("Customer") Is GPCUser Then
c = CType(Session("Customer"), GPCUser)
'Response.Redirect("update-details.aspx")
Else
c = New GPCUser
End If
If c.AccountNo = 0 Or c.AccountNo = CInt(System.Configuration.ConfigurationManager.AppSettings("WebsiteAccount")) Then
Else
Response.Redirect("update-details.aspx")
Exit Sub
End If
If Not Page.IsPostBack Then
Dim dt As DataTable = Nothing
dt = SqlHelper.ExecuteDataset(System.Configuration.ConfigurationManager.AppSettings("dbConn"), "x_ww_spGetCustomer", Request("custID")).Tables(0)
If Not dt Is Nothing Then
If dt.Rows.Count > 0 Then
Dim dr As DataRow = dt.Rows(0)
txtAccountName.Text = dr("AccountName")
txtFirstName.Text = dr("FirstName")
txtLastName.Text = dr("LastName")
txtEmail.Text = dr("Email")
If Request("custID") > 0 Then
Dim subscriptions As ContactSubscriptions = New ContactSubscriptions(Request("custID"))
' chkComputerPromotions.Checked = subscriptions.IsComputerPromotions
'chkElectronicPromotions.Checked = subscriptions.IsElectronicPromotions
chkGenernalNewsletters.Checked = subscriptions.IsGenernalNewsletters
End If
End If
End If
End If
End Sub
Protected Sub btnRegister_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnRegister.Click
' c.CreateCustomerDetails(txtAccountName.Text, txtFirstName.Text, txtLastName.Text, txtEmail.Text, txtAddress.Text, txtSuburb.Text, txtCityTown.Text, txtPostcode.Text, txtPhone.Text, txtMobile.Text, lstCountry.SelectedValue)
' c.GeneratedPassword = txtPassword.Text
' GPCUser.AddUpdateCustomer(c)
' ' Save the subscription details
'
'If Request("custID") > 0 and Request("AccNO") > 0 Then
Dim subscriptions As ContactSubscriptions = New ContactSubscriptions(Request("custID"))
'subscriptions.IsComputerPromotions = chkComputerPromotions.Checked
'subscriptions.IsElectronicPromotions = chkElectronicPromotions.Checked
subscriptions.IsGenernalNewsletters = chkGenernalNewsletters.Checked
subscriptions.Save()
'End IF
' Session("Customer") = c
'SendUpdateAccountEmailMessage(c.EmailCount)
'ClientScript.RegisterClientScriptBlock(Me.GetType(), "Thanks", "alert('Your Website PC account has been created. ');", False)
If chkGenernalNewsletters.Checked = True Then
Dim listID As Integer = 284662333
Dim isMember As Boolean = False
Dim newSession As New loginArgs()
newSession.username = "Not Relevant"
' Your VerticalResponse username
newSession.password = "Not Relevant"
'Your VerticalResponse password
' objLA.impersonate_user = "subaccount#emailaddress.com"; // If accessing or acting as a subaccount, uncomment this and replace it with the applicable email address.
newSession.session_duration_minutes = "120"
Dim [date] As DateTime = DateTime.Now
' This is generated by creating a Service Reference that points to the VerticalResponse WSDL.
Dim VRUser As New VRAPI()
' Let's try to log in. The login call will return a session ID, which we will use in all subsequent calls.
Dim sessionId As String = Nothing
Try
sessionId = VRUser.login(newSession)
Catch ex As System.Exception
lblMessage.Text = ex.ToString()
End Try
Dim getMember As New getListMemberByEmailAddressArgs()
getMember.session_id = sessionId
getMember.list_id = listID
getMember.email_address = txtEmail.Text
Try
VRUser.getListMemberByEmailAddress(getMember)
isMember = True
Catch ex As System.Exception
isMember = False
End Try
If (isMember = False) Then
Dim nMember As New ListMember()
nMember.list_id = listID
Dim memberData As NVPair() = New NVPair(2) {}
memberData(0) = New NVPair()
memberData(0).name = "email_address"
memberData(0).value = txtEmail.Text
memberData(1) = New NVPair()
memberData(1).name = "first_name"
memberData(1).value = txtFirstName.Text
memberData(2) = New NVPair()
memberData(2).name = "last_name"
memberData(2).value = txtLastName.Text
nMember.member_data = memberData
Dim objAL As New addListMemberArgs()
objAL.list_member = nMember
objAL.session_id = sessionId
Try
VRUser.addListMember(objAL)
Catch ex As System.Exception
txtEmail.Text = ex.ToString()
End Try
Else
pnlCreateAccount.Visible = False
lblMessage.Text = "You are already on our mailing list."
Exit Sub
End If
End If
pnlCreateAccount.Visible = False
lblMessage.Text = "you have successfully subscribed to Website PC email database."
End Sub
<System.Web.Services.WebMethod()> _
Public Shared Function ValidateEmail(email As String) As String
Dim wbClient As WebClient = New WebClient()
Dim strUrl As String = ConfigurationManager.AppSettings("WebsiteURLFull") + "/ajax/check_email_address.aspx?Email=" + email
Dim reqHTML As Byte()
reqHTML = wbClient.DownloadData(strUrl)
Dim objUTF8 As UTF8Encoding = New UTF8Encoding()
Dim output As String = objUTF8.GetString(reqHTML)
If String.IsNullOrEmpty(output) Then Return String.Empty
Return output
End Function
Private Sub SendMessage(fromEmail As String, fromEmailName As String, _
toEmails As String(), IsBodyHtml As Boolean, message As String, subject As String)
Dim mail As MailMessage = New MailMessage
mail.From = New MailAddress(fromEmail, fromEmailName)
For Each toEmail As String In toEmails
mail.To.Add(New MailAddress(toEmail))
Next
mail.Bcc.Add(fromEmail)
mail.IsBodyHtml = IsBodyHtml
mail.Subject = subject
mail.Body = message
Dim s As New SmtpClient(System.Configuration.ConfigurationManager.AppSettings("MailServer"))
s.Send(mail)
End Sub
Private Sub SendUpdateAccountEmailMessage(emailCount As Integer)
Dim subject As String = "ALERT : Website user subscribed to email database"
Dim message As String
message &= "Via page join-email" & vbCrLf & vbCrLf
message += "Account No: " & Request("custID") & vbCrLf
message += "Email : " & txtEmail.Text & vbCrLf
message += "Account Name : " & txtAccountName.Text & vbCrLf
message += "First Name : " & txtFirstName.Text & vbCrLf
message += "Last Name : " & txtLastName.Text & vbCrLf
message += "Email : " & txtEmail.Text & vbCrLf
message += "Subscribe to General Newsletters : " & chkGenernalNewsletters.Checked & vbCrLf
'message += "Subscribe to Computer Promotions: : " & chkComputerPromotions.Checked & vbCrLf
'message += "Subscribe to Electronic Promotions: : " & chkElectronicPromotions.Checked & vbCrLf
message &= vbCrLf & vbCrLf
message += "Regards" & vbCrLf & vbCrLf & "WebsitePC Admin Team"
SendMessage(ConfigurationManager.AppSettings("AccountDetailsUpdateEmail"), "Website PC", _
New String() {ConfigurationManager.AppSettings("AccountDetailsUpdateEmail")}, False, message, subject)
End Sub
End Class

Trouble passing results from DataReader to textbox

I am making an admin section that will allow access to several small SQL tables in my project.
I have repeaters set up to show my lists with a button to bring up a Modal for adding a new entry or editing an existing one. The code behind stores a value from the selected row, and then I would like to query my SQL Class to return a value to fill my text boxes. The code works back to the SQL Class and I can display a message box and get the proper results. I can't however get it to pass the value if the query back to the VB page to fill the text boxes.
Here is the Repeater
<%--Employee Repeater--%>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<HeaderTemplate>
<table class="display" id ="employeeList">
<thead>
<tr>
<th>
Name
</th>
<th>
Email
</th>
<th>
Update
</th>
</tr>
</thead>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%# Eval("name")%>
</td>
<td>
<%# Eval("email")%>
</td>
<td>
<asp:Button ID="cmdEditName" runat="server" Text="Edit/Delete" CommandArgument= '<%#Databinder.Eval(Container.DataItem, "id")%>' OnClick="EditName"/>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
My Code Behind
'Open Name Modal bound to repeater
Public Sub EditName(ByVal sender As Object, ByVal e As System.EventArgs)
Dim wLink As New Button
Edit = True
wLink = DirectCast(sender, Button)
txtEditId.Text = wLink.CommandArgument
SQL.RunReader("SELECT name from Admin_Contacts WHERE Admin_Contacts.id = '" & txtEditId.Text & "' ")
txtEditName.Text = results
SQL.RunReader("SELECT email from Admin_Contacts WHERE Admin_Contacts.id = '" & txtEditId.Text & "' ")
txtEditEmail.Text = results
ModalName.Show()
End Sub
And the code in my SQL Class
Public Function RunReader(ByVal Query As String) As String
Dim results As String = ""
Try
SQLCon.Open()
SQLCmd = New SqlCommand(Query, SQLCon)
Dim R As SqlDataReader = SQLCmd.ExecuteReader
While R.Read
results = (R(0))
'MsgBox is just to show that I am getting results
MsgBox(results)
End While
SQLCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
If SQLCon.State = ConnectionState.Open Then
SQLCon.Close()
End If
End Try
Dim results = SQL.RunReader("SELECT name from Admin_Contacts WHERE Admin_Contacts.id = '" & txtEditId.Text & "' ")
txtEditName.Text = results
Complete the runreader function with return statement
Public Function RunReader(ByVal Query As String) As String
Dim results As String = ""
Try
SQLCon.Open()
SQLCmd = New SqlCommand(Query, SQLCon)
Dim R As SqlDataReader = SQLCmd.ExecuteReader
While R.Read
results = (R(0))
'MsgBox is just to show that I am getting results
MsgBox(results)
End While
SQLCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
If SQLCon.State = ConnectionState.Open Then
SQLCon.Close()
End If
End Try
Return results
End Function
Then call this method as
Dim results = SQL.RunReader("SELECT name from Admin_Contacts WHERE Admin_Contacts.id = '" & txtEditId.Text & "' ")

Adding an ASP:DropDownList to select upload folder for ASPxUploadControl

I have a web form that uses a DevExpress ASPxUploadControl (v 8.3) to let our users upload documents to our server. I'm working on an enhancement that will allow them to select an upload folder for the document. These are not physical folders, but logical folders. I've added an ASP:DropDownList to the form, which I populate from the database with the names of the folders that user has set up. If the user selects the folder and then the attachment everything works fine. However, if they select the file to upload and then the folder, the file is uploaded automatically once the file has been selected, rather than waiting for them to click the Upload link. This does not allow them to change if they've selected the wrong document. Also, the old (last) value selected from the dropdownlist is used - it is not being updated to reflect the new choice I suspect there is a clash between server-side events and client-side events. Following is the relevant code. How can I prevent the page from automatically uploading the document?
Thanks!
Mike
<td class="style6" valign="middle">
<asp:Panel ID="Panel3" colspan="2" runat="server" Height="83px" Width="125px"
Style="margin-top: 0px">
<dxuc:ASPxUploadControl ID="uplImage" runat="server"
ClientInstanceName="uploader" Font-Size="Medium" Height="84px"
OnFileUploadComplete="uplImage_FileUploadComplete" ShowUploadButton="True"
Size="50" style="margin-top: 0px; margin-right: 2px;">
<ValidationSettings AllowedContentTypes="image/jpeg,image/gif,image/pjpeg,application/pdf,application/rtf,application/msword,application/vnd.ms-excel,application/csv,text/plain,text/csv,text/richtext,text/rtf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, audio/wav" MaxFileSize="4096000">
<ErrorStyle Font-Size="Smaller" />
</ValidationSettings>
<ClientSideEvents FileUploadComplete="function(s, e) {
if(e.isValid)
{
if(e.errorText != ''){
alert(e.errorText);
} else {
alert(e.callbackData);
}
}
}" />
<ValidationSettings AllowedContentTypes="image/jpeg, image/gif, image/pjpeg, application/pdf, application/rtf, application/msword, application/vnd.ms-excel, application/csv, text/plain, text/csv, text/richtext, text/rtf, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, audio/wav"
MaxFileSize="4096000">
<ErrorStyle Font-Size="Smaller" />
</ValidationSettings>
<ClientSideEvents FilesUploadComplete="function(s, e) {}" FileUploadComplete="function(s, e) {
if(e.isValid)
{
if(e.errorText != ''){
alert(e.errorText);
} else {
alert(e.callbackData);
}
}
}" FileUploadStart="function(s, e) {}" />
</dxuc:ASPxUploadControl>
</asp:Panel>
</td>
</tr>
<tr>
<td colspan="2" class="txtnote" align="center" style="height: 18px">
Allowed file types: jpeg, gif, pdf, rtf, doc, docx, txt, csv, xls, xlsx, wav
</td>
</tr>
<tr>
<td colspan="2" class="txtnote" align="center" style="height: 10px">
Maximum file size: 4Mb
</td>
</tr>
<tr>
<td></td>
<td>
<input id="chkPrivate" name="chkPrivate" value="1" type="checkbox"/>Private
(checking Private prevents Mgmt Co &Assn from viewing attachment via client
login.)</td></tr>
<tr class="aligncenter">
<th class="style5" align="center" colspan="2">
</th>
</tr>
<tr class="aligncenter">
<th class="style5" align="center" colspan="2">
<asp:Panel ID="Panel2" runat="server" Height="50px" Width="125px">
<%--<dxe:ASPxButton ID="Button1" runat="server" Font-Size="Medium" Text="Cancel">
<Paddings PaddingLeft="10px" PaddingRight="10px" />
</dxe:ASPxButton>--%>
<input type="button" id="btnReturn" class="frmBtnCommon" value="Back To Case" onclick="ReturnToCase();" />
</asp:Panel>
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim DAL As New DataAccessLayer
Dim dtFolders As New DataTable
GlobalVar.LoadData(Session("UserPKey"))
Session("CurrentPage") = "CaseAttchmt.aspx"
If Session("LoggedOn") = True And GlobalVar.ConnectString <> "" Then
CSSDefaultHTML = Session("CSS_Default")
DefaultIPHTML = Application("DefaultIP")
End If
SelKey = Request.QueryString("Case")
Header1.ConnectionStr = GlobalVar.ConnectString
Header1.HDLawFirm = GlobalVar.LawFirmDir
Header1.InsertHeader("Add File to a Case", 0, 0, SelKey, "width=100% align=center")
ClientKey = Session("ClientKey")
UploadDirectory = GlobalVar.LawFirmDir & "AttachFiles/Case" & Trim(Str(SelKey)) & "/"
If System.IO.Directory.Exists(GlobalVar.LawFirmDir & "AttachFiles/") = False Then
System.IO.Directory.CreateDirectory(GlobalVar.LawFirmDir & "AttachFiles")
End If
If System.IO.Directory.Exists(GlobalVar.LawFirmDir & "AttachFiles/Case" & Trim(Str(SelKey))) = False Then
System.IO.Directory.CreateDirectory(GlobalVar.LawFirmDir & "AttachFiles/Case" & Trim(Str(SelKey)))
End If
GlobalVar.SaveData(Session("UserPKey"))
dtFolders = DAL.GetClientFolders(Session("ClientKey"))
ddlFolders.DataSource = dtFolders
Dim lstFolders As ListItem
Dim i As Integer
Dim intValue As Integer
Dim strText As String
If Not Page.IsPostBack Then
ddlFolders.Items.Clear
intValue = 0
strText = "Attachments"
lstFolders = New ListItem(strText, intValue)
ddlFolders.Items.Add(lstFolders)
For i = 0 to dtFolders.Rows.Count - 1
intValue = dtFolders.Rows(i).Item("pKey")
strText = dtFolders.Rows(i).Item("FolderName")
lstFolders = New ListItem(strText, intValue)
ddlFolders.Items.Add(lstFolders)
Next
ddlFolders.SelectedIndex = 0
Session("FolderKey") = 0
End If
End Sub
Protected Function SavePostedFile() As String
Dim filename As String = ""
Dim tempFileName As String = ""
SelKey = Session("SelKey")
If Len(Trim(Session("ClientKey"))) = 4 then
UploadDirectory = "~/DATA/AR00" & Session("ClientKey") & "/AttachFiles/Case" & Trim(Str(SelKey)) & "/"
Else
UploadDirectory = "~/DATA/" & Trim(Session("LawFirm")) & "/AttachFiles/Case" & Trim(Str(SelKey)) & "/"
End If
filename = Trim(uplImage.FileName)
If filename <> "" Then
tempFileName = MapPath(UploadDirectory) & filename
uplImage.SaveAs(tempFileName)
End If
Return tempFileName
End Function
Protected Sub uplImage_FileUploadComplete(ByVal sender As Object, ByVal e As FileUploadCompleteEventArgs)
Dim FileExists As Boolean = False
UploadDirectory = "~/DATA/" & Trim(Session("LawFirm")) & "/AttachFiles/Case" & Trim(Str(Session("SelKey"))) & "/"
Dim FilePath As String = MapPath(UploadDirectory) & Trim(uplImage.FileName)
FileExists = CheckForFile(FilePath)
'urk : Added validation for checking filename length and filesize being uploaded 06/01/2010.
If (e.IsValid) Then
If (e.UploadedFile.FileName.Length > 100) Then
e.ErrorText = "The file name cannot be more than 100 characters long. Please shorten and retry."
ElseIf (e.UploadedFile.FileName.Contains("'") Or e.UploadedFile.FileName.Contains("&")) Then
e.ErrorText = "The file name cannot contain the apostrophe or ampersand characters."
ElseIf (e.UploadedFile.FileName.EndsWith(".aspx")) Or (e.UploadedFile.FileName.EndsWith(".ASPX")) Then
e.ErrorText = ".aspx files are not allowed for upload."
ElseIf FileExists = True Then
e.ErrorText = "A file with this name has already been uploaded. Please rename and try again."
Else
e.CallbackData = SavePostedFile()
If e.CallbackData <> "" Then
s_UpdateAttachData()
End If
e.CallbackData = "File: '" + e.UploadedFile.FileName + "' uploaded successfully."
End If
End If
End Sub
Private Sub s_UpdateAttachData()
Dim i_date As DateTime = Now.Date
Dim DAL As New DataAccessLayer
ClientKey = Session("ClientKey")
Dim pPrintBy As Integer = Session("UserPKey")
Dim PrintDate As DateTime = Now
Dim s As Boolean
Dim FullAttchPath As String
If Len(trim(ClientKey)) = 1 Then
FullAttchPath = "DATA/AR00000" + ClientKey.ToString + "/AttachFiles/Case" + SelKey.ToString + "/" + Trim(uplImage.FileName)
ElseIf Len(Trim(ClientKey)) = 4 then
FullAttchPath = "DATA/AR00" + ClientKey.ToString + "/AttachFiles/Case" + SelKey.ToString + "/" + Trim(uplImage.FileName)
Else
FullAttchPath = "DATA/AR0" + ClientKey.ToString + "/AttachFiles/Case" + SelKey.ToString + "/" + Trim(uplImage.FileName)
End If
If Request.Form("chkPrivate") <> "" Then
s = 1
Else
s = 0
End If
DAL.InsertCasesAttachPKey(ClientKey, SelKey, Trim(uplImage.FileName), Trim(uplImage.FileName), pPrintBy, PrintDate, s, FullAttchPath, Session("FolderKey"))
End Sub
Protected Function CheckForFile(ByVal Filename As String) As Boolean
If File.Exists(Filename) Then
Return True
Else
Return False
End If
End Function
Protected Sub ddlFolders_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles ddlFolders.SelectedIndexChanged
Session("FolderKey") = ddlFolders.SelectedValue
End Sub

How to declare a datasource in VB.NET?

I wrote an ASPX file in VB.NET. Originally this file ran successfully but after adding one additional parameter it now fails on "Name 'peType' is not declared".
This error does not make sense to me though because I have similar parameter, 'dType', which it does not error on. What is the cause of this error?
Here is some of my ASPX code file:
Sub Page_Load(Sender as Object, E as EventArgs)
If Not IsPostback Then
Dim TheMonthDate As Date = DateAdd(DateInterval.Month, -1, Today)
calStartDate.SelectedDate = CDate((TheMonthDate.Month) & "/1/" & Year(TheMonthDate)).ToString("MM/dd/yyyy")
calEndDate.SelectedDate = GlobalFunctions.GlobalF.MonthLastDate(CDate((TheMonthDate.Month) & "/1/" & Year(TheMonthDate)).ToString("MM/dd/yyyy"))
Dim arrType as New ArrayList()
Dim arrOrgUnit as New ArrayList()
Dim arrPEType as New ArrayList()
Dim peType As ListBox
arrType.Add("Product and Process")
arrType.Add("Product")
arrType.Add("Process")
dType.DataSource = arrType
dType.DataBind()
arrPEType.Add("-INC")
arrPEType.Add("-NC")
arrPEType.Add("-QC")
peType.DataSource = arrPEType
'peType.DataTextField = "DisplayColumnName"
'peType.DataValueField = "ValueColumnName"
peType.DataBind()
...
Dim TheType as String
Dim TheOrgUnit as String
Dim PE_Type as String
Select Case dType.SelectedValue
Case "Product and Process":
TheType = "((SMARTSOLVE.V_QXP_ALL_EXCEPTION.QXP_BASE_EXCEPTION)='PXP_PRODUCT_QXP' Or (SMARTSOLVE.V_QXP_ALL_EXCEPTION.QXP_BASE_EXCEPTION)='PXP_PROCESS_QXP')"
Case "Product":
TheType = "((SMARTSOLVE.V_QXP_ALL_EXCEPTION.QXP_BASE_EXCEPTION)='PXP_PRODUCT_QXP')"
Case "Process":
TheType = "((SMARTSOLVE.V_QXP_ALL_EXCEPTION.QXP_BASE_EXCEPTION)='PXP_PROCESS_QXP')"
End Select
Select Case peType.SelectedValue
Case "INC":
PE_Type = "substring(a.QXP_EXCEPTION_NO, charindex('-', a.QXP_EXCEPTION_NO)+1, 4)='INC'"
Case "NC":
PE_Type = "substring(a.QXP_EXCEPTION_NO, charindex('-', a.QXP_EXCEPTION_NO)+1, 4)='NC'"
Case "QC":
PE_Type = "substring(a.QXP_EXCEPTION_NO, charindex('-', a.QXP_EXCEPTION_NO)+1, 4)='QC'"
End Select
...
<td>
Product Exception Type:
</td>
<td>
<ASP:DROPDOWNLIST ID="peType" RUNAT="Server" AUTOPOSTBACK="true" />
</td>
But now my error is:
Object reference not set to an instance of an object
You missed setting the DataTextField and DataValueField property, when you tried to bind DataSource to your Dropdownlist, so set as follows:
peType.DataSource = arrPEType
peType.DataTextField = "DisplayColumnName"
peType.DataValueField = "ValueColumnName"
peType.DataBind()

Resources