How to send an email via outlook with .asp - asp.net

I'm not to familiar with this but i have done similar in the past. Basically i want to have an html, or .asp page with a simple form for the user to input data. I've accomplished this in VB.net with the following:
Imports Outlook = Microsoft.Office.Interop.Outlook
Private Sub cmdFax_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)Handles cmdFax.Click
Dim oApp As Outlook._Application
oApp = New Outlook.Application()
Dim oMsg As Outlook._MailItem
oMsg = oApp.CreateItem(Outlook.OlItemType.olMailItem)
oMsg.Subject = ""
oMsg.Body = "" & vbCr & vbCr
If Len(txtEmail.Text) > 0 Then
oMsg.To = Me.txtEmail.Text
Else
oMsg.To = "[Fax:" & Me.txtAttn.Text & " # " & Me.txtFaxNum.Text & "]"
End If
Dim sSource As String = "C:\ValidPath.txt"
Dim sDisplayName As String = "Hello.txt"
Dim sBodyLen As String = oMsg.Body.Length
Dim oAttachs As Outlook.Attachments = oMsg.Attachments
Dim oAttach As Outlook.Attachment
If Len(Me.TextBox1.Text) > 0 Then
oAttach = oAttachs.Add(Me.TextBox1.Text)
Else
End If
oAttachs.Add(Me.cboForm.SelectedValue)
oMsg.Send()
oApp = Nothing
oMsg = Nothing
oAttach = Nothing
oAttachs = Nothing
'MsgBox("Your Fax Has Been Sent Successfully")
lblStatus.Text = "Fax Sent"
'lblStatus.Text = "Ready"
End If
End Sub
Is there anyway to accomplish the same thing using .asp? or is there an easier way to do this using a contact form and .asp page? I'm just trying to avoid using an external mail server and have the form send from the actual user.
Open to any suggestions!

There's no reason your code won't work when called from an ASP.NET application.
Your requirements need to be better articulated, but the "norrmal" way to do things is via the System.Net.Mail namespace instead of invoking Outlook.
If you don't want to use an external mail server, configure the built-in IIS SMTP Server to use the same account settings as Outlook.

Related

how to send an email using SendGrid V3 to multiple recipients, in a .NET app

It sends to one ok. But not to 2 or more. I've tried separating addresses by , and ; and space in the to_addr string, but failed.
What format does class EmailAddress expect for multiple addresses?
public async sub send_message( msg_subject, msg_body, from_addr_text, to_addr_text, optional commands = "")
dim apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY")
dim client as new SendGridClient( apiKey, , , "v3", )
dim from = new EmailAddress( from_addr_text, "INSTRUMENT")
dim subject = msg_subject
if subject = ""
subject = " " ' won't send if empty
End If
dim to_addr = new EmailAddress( to_addr_text, "INSTRUMENT")
dim plainTextContent = msg_body
dim htmlContent = "<strong>" & msg_body & "</strong>"
dim msg = MailHelper.CreateSingleEmail(from, to_addr, subject, plainTextContent, htmlContent)
dim response = await client.SendEmailAsync(msg)
if instr( commands, "SKIP POPUPS") ' TEST TEXT MSG !!!
exit sub
End If
popup_information( "MESSAGE SENDING", "Sent..." & vbcrlf & vbcrlf & "SUBJECT: " & vbcrlf & subject & vbcrlf & vbcrlf & "BODY: " & vbcrlf & msg_body )
end sub
Not sure which SDK version are you using , but if you follow the Sendgrid V3 api SDK for C# , you should find a method like below in the MailHelper class
public static SendGridMessage CreateSingleEmailToMultipleRecipients(EmailAddress from, List<EmailAddress> tos, string subject,string plainTextContent,string htmlContent)
which accepts a List<EmailAddress> to send email to multiple recipients. So instead of using the below line in your code
dim msg = MailHelper.CreateSingleEmail(from, to_addr, subject, plainTextContent, htmlContent)
you should use the below code
var to_addr = new List<EmailAddress>();
to_addr.Add(new EmailAddress( to_addr_text, "INSTRUMENT"));
to_addr.Add(new EmailAddress( "secondperson#test.com", "secondperson")); // you can add multiple email in this list
and then you can use to_addr in the code below
dim msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, to_addr, subject, plainTextContent, htmlContent)
Pardon me for the example in C# but the same should be applicable for your VB.NET code
The stack overflow answer here shows how to implement SendGrid using dependency injection into a Net 6 Web API application using controllers.
The scenario of sending an email to multiple recipients is covered in the referenced example code here: https://github.com/Davidmendoza1987/dotnet-sendgrid-examples

Print SSRS Report from Code (asp.net)

I have found good information on how to automatically download a file to the client advertised as a solution of how to print using code
(https://forums.asp.net/t/1233841.aspx?How+do+I+print+from+Reporting+Services+AUTOMATICALLY+in+VB+Net+web+app+)
but what I need to do is have the code print the document without the user interacting.
From what I have found it appears this can not be done as one might casually think. ReportViewer for example does not have a 'print' method.
The only two solutions appears to be to use ProcessStart (which then means saving the file to the file system before printing which I dont want to do)
or maybe (will be researching this today) create a subscription using code and then delete it later.
You are not able to print a report directly from your asp.net page. The reason for this is security. If it allowed you to send a file through the network and onto the clients computer, and then search the computer for a printer, this could cause major security issues. The report viewer does have a print icon, but this disappears when you deploy the project and run the page remotely. I have faced the same issue in the past and found it best to just export the report to say PDF and allow the user to Download it. I have used the below code to accomplish this task in the past:
Private Sub CreatePDFMatrix(fileName As String)
' ReportViewer1.LocalReport.DataSources.Clear()
Dim adapter As New ReportDataSetTableAdapters.vwPrintTagsTableAdapter
Dim table As New ReportDataSet.vwPrintTagsDataTable
Dim month = MonthName(Date.Today.Month)
Dim year = Date.Today.Year
Dim p(1) As ReportParameter
Dim warnings() As Warning
Dim streamIds As String()
Dim mimeType As String = String.Empty
Dim encoding As String = String.Empty
Dim extension As String = String.Empty
Dim adpt2 As New ReportDataSetTableAdapters.vwPrintTagsTableAdapter
adapter.FillForMainReport(table, DropDownList1.SelectedValue, g_Company, g_Division)
Me.ReportViewer1.LocalReport.DataSources.Add(New ReportDataSource("DataSet1", CType(table, DataTable))) 'Add(New ReportDataSource("ReportingData", CType(table, DataTable)))
Me.ReportViewer1.DataBind()
Dim viewer = ReportViewer1
viewer.ProcessingMode = ProcessingMode.Local
viewer.LocalReport.ReportPath = "Report1.rdlc"
p(0) = New ReportParameter("MonthYear", month & "-" & year)
Dim check = DropDownList1.SelectedValue
ReportViewer1.LocalReport.SetParameters(p(0))
p(1) = New ReportParameter("Location", DropDownList1.SelectedValue)
ReportViewer1.LocalReport.SetParameters(p(1))
Try
Dim bytes As Byte() = viewer.LocalReport.Render("PDF", Nothing, mimeType, encoding, ".pdf", streamIds, warnings)
Response.Buffer = True
Response.Clear()
Response.ContentType = mimeType
Response.AddHeader("content-disposition", Convert.ToString((Convert.ToString("attachment; filename=") & fileName) + ".") & extension)
Response.BinaryWrite(bytes)
' create the file
Response.Flush()
Catch ex As Exception
Debug.Print(ex.ToString)
End Try
End Sub

Pull Outlook OfficeLocation using Alias

While referencing Return list of names and email address from outlook to vb.net listbox I am trying to fill in a ASP:Textbox with the Office Location of the user.
Currently I pull the current logged in user. The user's username on their PC is also their Outlook Alias. With that being said, I am trying to use the username/Alias to pull the Office location within Outlook. I currently have the following issue with my coding:
'get logged in user(works)
Dim username As String
Dim User As System.Security.Principal.IPrincipal
User = System.Web.HttpContext.Current.User
username = User.Identity.Name.Substring(3)
'Office Location of User
Dim itemx As String
'Create an Outlook application.
Dim oApp As Outlook._Application = New Outlook.Application()
'Get the MAPI namespace.
Dim oNS As Outlook.NameSpace = oApp.Session
'Get the Global Address List.
Dim oALs As Outlook.AddressLists = oNS.AddressLists
Dim oGal As Outlook.AddressList = oALs.Item(1)
'Get all the entries.
Dim oEntries As Outlook.AddressEntries = oGal.AddressEntries
For Each entry In oEntries
If oEntries.GetExchangeUser.Alias = username Then
itemx = oEntries.GetExchangeUser.OfficeLocation
End If
Next
Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.
If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution. Read more about that in the Considerations for server-side Automation of Office article in MSDN.
As a workaround you may consider using EWS, see EWS Managed API, EWS, and web services in Exchange for more information. Or just a low-level API on which Outlook is based on - Extended MAPI.
Main thing that I learned was that you need a password and username to access outlook.
Get user ID from PC (Alias for Outlook):
Dim usernameQuery As String
Dim UserQ As System.Security.Principal.IPrincipal
UserQ = System.Web.HttpContext.Current.User
usernameQuery = User.Identity.Name.Substring(3).ToUpper
UserText.Text = usernameQuery
Then:
Call function like so:
'outlook office location **************************************************
LocationText.Text = GetUserInfo(usernameQuery, "physicaldeliveryofficename")
'OTHER OPTIONS YOU CAN QUERY
'Dim svalue As String = GetUserInfo(UserAccount, "mail")
'Dim svalue As String = GetUserInfo(UserAccount, "givenName")
'Dim svalue As String = GetUserInfo(UserAccount, "sn")
'Dim svalue As String = GetUserInfo(UserAccount, "l")
'Dim svalue As String = GetUserInfo(UserAccount, "st")
'Dim svalue As String = GetUserInfo(UserAccount, "streetAddress")
'Dim svalue As String = GetUserInfo(UserAccount, "postalCode")
'Dim svalue As String = GetUserInfo(UserAccount, "telephoneNumber")
'Dim svalue As String = GetUserInfo(useraccount, "co")
'txtName.Text = GetUserInfo(UserAccount, "givenName") & " " & GetUserInfo(UserAccount, "sn")
'txtPhone.Text = GetUserInfo(UserAccount, "telephoneNumber")
'********************************************************************************
Function:
Public Function GetUserInfo(ByVal inSAM As String, ByVal inType As String) As String
Try
Dim sPath As String = "LDAP://"full_path"/DC="path_value",DC="path_value",DC="path_value" "
Dim SamAccount As String = Right(inSAM, Len(inSAM) - InStr(inSAM, "\"))
Dim myDirectory As New DirectoryEntry(sPath, "username", "password") 'pass the user account and password for your Enterprise admin.
Dim mySearcher As New DirectorySearcher(myDirectory)
Dim mySearchResultColl As SearchResultCollection
Dim mySearchResult As SearchResult
Dim myResultPropColl As ResultPropertyCollection
Dim myResultPropValueColl As ResultPropertyValueCollection
'Build LDAP query
mySearcher.Filter = ("(&(objectClass=user)(samaccountname=" & SamAccount & "))")
mySearchResultColl = mySearcher.FindAll()
'I expect only one user from search result
Select Case mySearchResultColl.Count
Case 0
Return "Null"
Exit Function
Case Is > 1
Return "Null"
Exit Function
End Select
'Get the search result from the collection
mySearchResult = mySearchResultColl.Item(0)
''Get the Properites, they contain the usefull info
myResultPropColl = mySearchResult.Properties
If myResultPropColl.Contains(inType) Then
myResultPropValueColl = myResultPropColl.Item(inType)
Return CStr(myResultPropValueColl.Item(0))
End If
'displayname, mail
'Retrieve from the properties collection the display name and email of the user
'myResultPropValueColl = myResultPropColl.Item(inType)
'Return CStr(myResultPropValueColl.Item(0))
Catch ex As System.Exception
End Try
Return "Null"
End Function
FYI-
full_path = "value"."value"."value"

How to print a server side text file on a client printer programically

I have a server side application which creates a series of text files on the server. I need to allow a user to print one or more of the files directly on the client printer by clicking a button on a web page. That should bring up a printer selection window and then commence printing the selected web pages. I can handle the file selection and the printer selection windows but have not been able to get the files to print. I located code on Code Project (http://www.codeproject.com/Tips/689325/Send-PDF-files-directly-to-client-printer-without) which was described as doing exactly what I need but for for PDF files. I have attempted to adapt it to text files and the code runs without visible error, but nothing arrives at the printer and I do not know how to locate what happens after the code executes the value attribute of the Object tag of the web pages source code (see below). I program in VB.Net.
Here is the object tag in the source code:
<object id = "Object1" name="Txt1"
type="file/txt" width="1" height="1" >
<param name='SRC' value='<%= SReportFileName %>'/>
</object>
Here is the code from the code behind file:
Partial Class ViewResults_PrintingReports
Inherits System.Web.UI.Page
Public SReportFileName As String = ""
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim PathName As String = ""
Dim Uname As String = ""
Dim Iyr As String = ""
Dim Iwld As String = ""
Dim Iqtr As String = ""
Dim FName As String = ""
Dim CNumber As String = ""
Uname = "UserName"
Iyr = "3"
Iqtr = "1"
FName = "ReportA"
CNumber = "1"
Iwld = "1"
' Dim cs As ClientScriptManager = Page.ClientScript
PathName = "~/Competitions/" & Uname & "/BP/" & "World" & Iwld & "/Reports/QtrRpts" & Iwld & "." & Iyr & Iqtr & "/" & FName & "." & Iwld & CNumber & ".txt"
SReportFileName = PathName '// temp/mypdf.pdf
Try
ClientScript.RegisterStartupScript(GetType(Page), "MessagePopUp", "<script language=text/javascript>document.Txt1.printAll()</script>")
Catch ex As Exception
MsgBox("Problem printing file", , ex.Message)
End Try
End Sub
End Class
Any help would be appreciated.
You need to call javascript.
Here is the javascript
function PrintFile(FilePath) {
var printWin = window.open(FilePath, '','left=0,top=0,width=700,height=700,status=0');
printWin.focus();
printWin.print();
}
This is the codebehind of the button
Dim FilePath As String
FilePath = "This is your File Path"
Dim PrintFile As String
PrintFile = "PrintFile('" & FilePath & "')"
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "ntmtch", PrintFile, True)

Activation Email/Link Not Working

I'm trying to send an activation email and have the user activate their account by clicking on the link provided. I have been tweaking it based on open source code I've been looking at online, however it has recently stopped sending the email without giving any errors. Here is the sign up form with the send email function:
Imports System.Data.SqlClient
Imports System.Data.Sql
Imports System.Data.SqlTypes
Imports System.Data
Imports System.Configuration
Imports System.Net.Mail
Imports System.Net
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Public Class WebForm1
Inherits System.Web.UI.Page
Dim boolCar As Object
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
If txtEmailAddress.Text.Trim.EndsWith("#umary.edu") Or txtPassword.Text.Trim = txtRetypePassword.Text.Trim Then
Dim con As New SqlConnection
Dim cmdEmail As New SqlCommand
Dim cmdRegistration As New SqlCommand
Dim EmailCount As Integer = 0
Try
con.ConnectionString = "Data Source=SERVERNAME;Initial Catalog=StudentGov;User ID=sa;Password=Password1"
con.Open()
cmdEmail = New SqlCommand("SELECT COUNT(UMaryEmail) As EmailCount FROM RegisteredUsers WHERE UMaryEmail='" & txtEmailAddress.Text.Trim & "'", con)
EmailCount = cmdEmail.ExecuteScalar()
If EmailCount = 0 Then
' Declare database input variables
Dim userId As Integer = 0
Dim firstName As String = txtFirstName.Text
Dim lastName As String = txtLastName.Text
Dim hometown1 As String = txtHometown1.Text
Dim state1 As String = txtState1.Text
Dim zip1 As String = txtZipCode1.Text
Dim hometown2 As String = txtHometown2.Text
Dim state2 As String = txtState2.Text
Dim zip2 As String = txtZipCode2.Text
Dim phoneNum As String = txtPhoneNumber.Text
Dim emailAddress As String = txtEmailAddress.Text
Dim password As String = txtPassword.Text
Dim boolCar As Boolean = False
Dim boolUmary As Boolean = False
If radYesNo.SelectedIndex = 0 Then
boolCar = True
Else
boolCar = False
End If
' Define the command using parameterized query
cmdRegistration = New SqlCommand("INSERT INTO RegisteredUsers(FirstName, LastName, Hometown1, State1, ZIP1, Hometown2, State2, ZIP2, PhoneNum, UMaryEmail, Password, Car) VALUES (#txtFirstName, #txtLastName, #txtHometown1, #txtState1, #txtZipCode1, #txtHometown2, #txtState2, #txtZipCode2, #txtPhoneNumber, #txtEmailAddress, #txtPassword, #RadYesNo)", con)
' Define the SQL parameter '
cmdRegistration.Parameters.AddWithValue("#txtFirstName", txtFirstName.Text)
cmdRegistration.Parameters.AddWithValue("#txtLastName", txtLastName.Text)
cmdRegistration.Parameters.AddWithValue("#txtHometown1", txtHometown1.Text)
cmdRegistration.Parameters.AddWithValue("#txtState1", txtState1.Text)
cmdRegistration.Parameters.AddWithValue("#txtZipCode1", txtZipCode1.Text)
cmdRegistration.Parameters.AddWithValue("#txtHometown2", txtHometown2.Text)
cmdRegistration.Parameters.AddWithValue("#txtState2", txtState2.Text)
cmdRegistration.Parameters.AddWithValue("#txtZipCode2", txtZipCode2.Text)
cmdRegistration.Parameters.AddWithValue("#txtPhoneNumber", txtPhoneNumber.Text)
cmdRegistration.Parameters.AddWithValue("#txtEmailAddress", txtEmailAddress.Text)
cmdRegistration.Parameters.AddWithValue("#txtPassword", txtPassword.Text)
cmdRegistration.Parameters.AddWithValue("#RadYesNo", boolCar)
cmdRegistration.ExecuteNonQuery()
SendActivationEmail(userId)
Response.Redirect("RegistrationSuccess.aspx")
Else
' Duplicate Email Exist Error Message
MsgBox("Email address already supplied.")
End If
' Catch ex As Exception (Not needed)
' Error Executing One Of The SQL Statements
Finally
con.close()
End Try
Else
' Throw Error Message
MsgBox("Email input error")
End If
End Sub
Private Sub SendActivationEmail(userId As Integer)
Dim sqlString As String = "Server=SERVERNAME;Database=StudentGov;UId=sa;Password=Password1;"
Dim ActivationCode As String = Guid.NewGuid().ToString()
Dim ActivationUrl As String = Server.HtmlEncode("http://localhost:63774/ActivateAccount.aspx?userId=" & FetchUserId(txtEmailAddress.ToString) & "&txtEmailAddress=" & txtEmailAddress.ToString & "&ActivationCode=" & ActivationCode.ToString)
Using con As New SqlConnection(sqlString)
Using sqlCmd As New SqlCommand("UPDATE RegisteredUsers SET UserId = '" + userId.ToString + "', ActivationCode = '" + ActivationCode.ToString + "' WHERE UMaryEmail='" + txtEmailAddress.Text + "';")
Using sda As New SqlDataAdapter()
sqlCmd.CommandType = CommandType.Text
sqlCmd.Parameters.AddWithValue("#UserId", userId)
sqlCmd.Parameters.AddWithValue("#ActivationCode", ActivationCode)
sqlCmd.Connection = con
con.Open()
sqlCmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Using
Using mm As New MailMessage("****#outlook.com", txtEmailAddress.Text)
mm.Subject = "Account Activation"
Dim body As String = "Hello " + txtFirstName.Text.Trim() + ","
body += "<br /><br />Please click the following link to activate your account"
body += "<br /><a href='" & ActivationUrl & "'>Click here to activate your account.</a>"
body += "<br /><br />Thanks"
mm.Body = body
mm.IsBodyHtml = True
Dim smtp As New SmtpClient()
smtp.Host = "smtp.live.com"
smtp.EnableSsl = True
Dim NetworkCred As New NetworkCredential("****#outlook.com", "****")
smtp.UseDefaultCredentials = True
smtp.Credentials = NetworkCred
smtp.Port = 587
Try
smtp.Send(mm)
Catch ex As Exception
MsgBox("Email was not sent")
End Try
End Using
End Sub
Private Function FetchUserId(emailAddress As String) As String
Dim cmd As New SqlCommand()
Dim con As New SqlConnection("Data Source=SERVERNAME;Initial Catalog=StudentGov;User ID=sa;Password=Password1")
cmd = New SqlCommand("SELECT UserId FROM RegisteredUsers WHERE UMaryEmail=#txtEmailAddress", con)
cmd.Parameters.AddWithValue("#txtEmailAddress", emailAddress)
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim userId As String = Convert.ToString(cmd.ExecuteScalar())
con.Close()
cmd.Dispose()
Return userId
End Function
End Class
And here is the AccountActivation page:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Public Class ActivateAccount
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
ActivateMyAccount()
End If
End Sub
Private Sub ActivateMyAccount()
Dim con As New SqlConnection()
Dim cmd As New SqlCommand()
Try
con.ConnectionString = "Data Source=CISWEB\UMCISSQL2008;Initial Catalog=StudentGov;User ID=sa;Password=Password1"
If (Not String.IsNullOrEmpty(Request.QueryString("UserId"))) And (Not String.IsNullOrEmpty(Request.QueryString("UMaryEmail"))) Then
'approve account by setting Is_Approved to 1 i.e. True in the sql server table
cmd = New SqlCommand("UPDATE RegisteredUsers SET AccountActivated=1 WHERE UserId=#UserId AND UMaryEmail=#txtEmailAddress", con)
cmd.Parameters.AddWithValue("#UserId", Request.QueryString("UserId"))
cmd.Parameters.AddWithValue("#txtEmailAddress", Request.QueryString("UMaryEmail"))
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.ExecuteNonQuery()
Response.Write("You account has been activated. You can <a href='SignIn.aspx'>Sign in</a> now! ")
End If
Catch ex As Exception
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True)
Return
Finally
con.Close()
cmd.Dispose()
End Try
End Sub
End Class
As you may be able to tell already, I am flummoxed. With no error messages I'm receiving, I don't know why the SendActivationEmail function is no longer working. Someone help please! :(
Hi FlummoxedUser are you sure that have you checked your code as well ????
Take a look here :
Dim ActivationUrl As String = Server.HtmlEncode("http://localhost:63774/ActivateAccount.aspx?userId=" & FetchUserId(txtEmailAddress.ToString) & "&txtEmailAddress=" & txtEmailAddress.ToString & "&ActivationCode=" & ActivationCode.ToString)
I think is better use httputility.urlEncode/Decode for this stuff where it use it to filter only the result of each function or single variable.
Second one take care at your code above
this is in your page :
If (Not String.IsNullOrEmpty(Request.QueryString("UserId"))) And (Not String.IsNullOrEmpty(Request.QueryString("UMaryEmail")))
where have you found "UmaryEmail" key in your querystring parameters?????
Check it and you will solve your issue but check also in cmd and so on in activation page or you will make some issues :)
I hope it help you and if it solves your issue mark this as answer.
UPDATE :
> Dim ActivationUrl As String = Server.HtmlEncode("http://localhost:63774/ActivateAccount.aspx?userId=" & FetchUserId(txtEmailAddress.ToString) & "&txtEmailAddress=" & txtEmailAddress.ToString & "&ActivationCode=" & ActivationCode.ToString)
with this task you create yout activation link which will be something like
http://localhost:63774/ActivateAccount.aspx?userId=1&txtEmailAddress=email#pippo&ActivationCode=123456
Now what's append when click on that link server handle request and create a collection data which include all the keys within your querystring
In effect you can use request.QueryString to check/retrieve values from each keys. So you can use as you did request.Querystring("keyname") to get the value for that particular parameter BUT in your case you check for a key which are not passed into the link. Pay attention that you have setup only 3 keys which are
UserID
txtEmailAddress
ActivationCode
there's no "UMaryEmail" key in request query string
Also another important stuff NEVER PASS IN QUERY STRING DATABASE FIELD :) use fantasy name or shortname which not reflect database field
example :
UserID => uid
ActivatioCode = token,acd,cd or anything you want
txtEmailAddress= email, em or any other name
Now activation page issue when you try to check your value use an if statement where check for userid key and UMaryEmail where userid could be matched coz it exist in query string but UmaryEmail is not into the request.querystring you have not provided it so if fails and nothing has been shown in page.
Here your Activation Sub revisited with some comments to better understand :
Private Sub ActivateMyAccount()
'Checking you keys in querystring
If Request.QueryString.AllKeys.Contains("Userid") AndAlso Request.QueryString.AllKeys.Contains("txtEmailAddress") Then
'here we assume that keys exist and so we can proceed with rest
If (Not String.IsNullOrEmpty(Request.QueryString("UserId"))) And (Not String.IsNullOrEmpty(Request.QueryString("txtEmailAddress"))) Then
'no we can proceed to make other stuff
'Another stuff place you connection string within connection string section in webconfig in order to make a simple request like this one :
'classic example for create a connection with web config file
' Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("yourconnectionstringname").ToString)
Using con As New SqlConnection("Data Source=CISWEB\UMCISSQL2008;Initial Catalog=StudentGov;User ID=sa;Password=Password1")
If con.State = ConnectionState.Closed Then con.Open()
Dim sqlQuery As String = "UPDATE RegisteredUsers SET AccountActivated=1 WHERE UserId=#UserId AND UMaryEmail=#txtEmailAddress"
Using cmd As New SqlCommand(sqlQuery, con)
Try
With cmd
.Parameters.AddWithValue("#UserId", Request.QueryString("UserId"))
.Parameters.AddWithValue("#txtEmailAddress", Request.QueryString("txtEmailAddress"))
.ExecuteNonQuery()
Response.Write("You account has been activated. You can <a href='SignIn.aspx'>Sign in</a> now! ")
End With
Catch ex As Exception
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('We apologize but something is gone wrong;our techs are checking the issue.Best regards etc etc etc');", True)
End Try
End Using
End Using
Else
Response.Write("<h1>invalid activation links!!</h1>")
End If
Else
Response.Write("<h1>invalid activation links!!</h1>")
End If
End Sub
If your query is right it should work at first shot :)
Take a try and let me know and if it solve your issue please mark it as answer
UPDATE 2:
Your actual code is :
Dim ActivationUrl As String = Server.HtmlEncode("localhost:63774/ActivateAccount.aspx?userId=" & HttpUtility.UrlEncode(FetchUserId(txtEmailAddress.ToString)) & "&txtEmailAddress=" & HttpUtility.UrlEncode(txtEmailAddress.ToString) & "&ActivationCode=" & HttpUtility.UrlEncode(ActivationCode.ToString))
But is all wrong let me explain:
Declar your variable : Dim ActivationUrl as string it is ok
Then built url so :
="http://localhost:63774/ActivateAccount.aspx?userId=" & HttpUtility.UrlEncode(FetchUserId(txtEmailAddress.text.tostring)) & "&txtEmailAddress=" & HttpUtility.UrlEncode(txtEmailAddress.text.tostring) & "&ActivationCode=" & HttpUtility.UrlEncode(ActivationCode.ToString))
Where take a look to piece of code which is your : 'HttpUtility.UrlEncode(txtEmailAddress.ToString)' in this manner you are passing a value system type object which is a textbox to pass textbox value you need to access to its .Text property like txtEmailAddress .Text
Change as per my code above and it will work (if your procedure is right)
**UPDATE CODE 3 **
Change your code with this.§be carefull don't change anything copy and paste all ActivateMyAccount Sub and delete your old one
Private Sub ActivateMyAccount()
'Checking you keys in querystring
If Request.QueryString.AllKeys.Contains("userId") And Request.QueryString.AllKeys.Contains("txtEmailAddress") Then
'here we assume that keys exist and so we can proceed with rest
If (Not String.IsNullOrEmpty(Request.QueryString("userId"))) And (Not String.IsNullOrEmpty(Request.QueryString("txtEmailAddress"))) Then
'no we can proceed to make other stuff
'Another stuff place you connection string within connection string section in webconfig in order to make a simple request like this one :
'classic example for create a connection with web config file
' Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("yourconnectionstringname").ToString)
Using con As New SqlConnection("Data Source=CISWEB\UMCISSQL2008;Initial Catalog=StudentGov;User ID=sa;Password=Password1")
If con.State = ConnectionState.Closed Then con.Open()
Dim sqlQuery As String = "UPDATE RegisteredUsers SET AccountActivated=1 WHERE UserId=#UserId AND UMaryEmail=#txtEmailAddress"
Using cmd As New SqlCommand(sqlQuery, con)
Try
With cmd
cmd.Parameters.AddWithValue("#UserId", Request.QueryString("userId"))
cmd.Parameters.AddWithValue("#txtEmailAddress", Request.QueryString("txtEmailAddress"))
cmd.ExecuteNonQuery()
Response.Write("You account has been activated. You can <a href='SignIn.aspx'>Sign in</a> now! ")
End With
Catch ex As Exception
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('We apologize but something is gone wrong;our techs are checking the issue.Best regards etc etc etc');", True)
End Try
End Using
End Using
Else
Response.Write("<h1>invalid activation links!! bad query string</h1>")
End If
Else
Response.Write("<h1>invalid activation links!! bad not string</h1>")
End If
End Sub

Resources