SendGrid Marketing Email Delay? - asp.net

Steps
Create recipient list
Create marketing Email
Add emails to recipient list
Assign recipient list to marketing email
When I debug slowly, i managed to passed all steps with success message from sendgrid.
But in non debug mode, although i added emails to recipient list success(results return from sendgrid), when in step 4, i get results return List without recipients. I refresh the browser and saw the emails in the recipient list as well.
I tried to put timer.interval before start to process step 4 but also get the same results return.
VB ProcessHandler Code
' Add email and name to recipient list
If oSendMarketingEmail.AddEmailToList(oItemDetails.Email, oItemDetails.Full_Name, sRecipientList) = False Then Exit Try
' Wait for the email and name added to recipient list
Dim timer As New Timers.Timer
timer.Interval = 20000
' Assigning recipient list to marketing email
If oSendMarketingEmail.AddListToMarketingEmail(sMarketingEmailName, sRecipientList) = False Then Exit Try
VB Function Code
Public Function AddEmailToList(sEmailAddress As String, sName As String, sRecipientList As String) As Boolean
Dim ResultsHTML As String = ""
Dim URL As String = (Convert.ToString("http://sendgrid.com/api/newsletter/lists/email/add.xml?list=") & sRecipientList) + "&data=" + "{""email"":""" + sEmailAddress + """,""name"":""" + sName + """}" + "&api_user=" + SendGridUserName + "&api_key=" + SendGridPassword
Dim SendGridResponse As String = PerformHTTPGet(URL)
ResultsHTML += (Convert.ToString("Adding email to List: ") & SendGridResponse) + "<br/>"
' Check respond status - success
If Not ResultsHTML.Contains("insert") Then logger.log.Info(ResultsHTML) : Return False Else Return True
End Function
Public Function AddListToMarketingEmail(sMarketingEmailName As String, sRecipientList As String) As Boolean
Dim ResultsHTML As String = ""
'Assign list to marketing email
Dim URL As String = (Convert.ToString((Convert.ToString("http://sendgrid.com/api/newsletter/recipients/add.xml?name=") & sMarketingEmailName) + "&list=") & sRecipientList) + "&api_user=" + SendGridUserName + "&api_key=" + SendGridPassword
Dim SendGridResponse As String = PerformHTTPGet(URL)
ResultsHTML += (Convert.ToString("Assigning Marketing Email to List: ") & SendGridResponse) + "<br/>"
' Check respond status - success
If Not ResultsHTML.Contains("success") Then logger.log.Info(ResultsHTML) : Return False
End Function

In SendGrid, the list-count can take a little while to update. One way to "force" it is to query the full list, which triggers the system to count through, and will update the count, which will then allow you to attach it properly.

Related

CURL from ASP.Net (VB.Net) PayPal

https://developer.paypal.com/docs/archive/express-checkout/ht-ec-parallelPayments/
Been trying to implement this on ISS with ASP.Net & VB.Net and I am not sure how to properly build the request token so that this can work and be utilized.
This is what I have come up with, but the API request will not process getting this:
The request was aborted: Could not create SSL/TLS secure channel.
still not working
Private Sub btnSUBMIT_Click(sender As Object, e As EventArgs) Handles btnSUBMIT.Click
Dim NVP As New Dictionary(Of String, String) ''Api Name-Value-Pair parameters
''define paypal SANDBOX server
Dim paypalApiServerUrl As String = "https://api-3t.sandbox.paypal.com/nvp"
NVP.Add("USER", "fixed") ' = Caller_ID '## the PayPal User ID Of the caller account
NVP.Add("PWD", "12345678") ' PWD = Caller_Pswd '## the caller account Password
NVP.Add("SIGNATURE", "solved") ' Signature = Caller_Sig '## the caller account Signature
NVP.Add("METHOD", METHOD) ' METHOD = SetExpressCheckout '## API operation
NVP.Add("RETURNURL", RETURNURL) ' RETURNURL = https : //example.com/success.html '## URL displayed to buyer after authorizing transaction
NVP.Add("CANCELURL", CANCELURL) ' CANCELURL = https : //example.com/canceled.html '## URL displayed to buyer after canceling transaction
NVP.Add("Version", "93") ' Version = 93 '## API version
NVP.Add("PAYMENTREQUEST_0_CURRENCYCODE", PAYMENTCURRENCYCODE) ' ## Start primary level information For first payment
NVP.Add("PAYMENTREQUEST_0_AMT", "250") '
NVP.Add("PAYMENTREQUEST_0_ITEMAMT", "225") '
NVP.Add("PAYMENTREQUEST_0_TAXAMT", "25") '
NVP.Add("PAYMENTREQUEST_0_PAYMENTACTION", SALEPAYMENTACTION) '
NVP.Add("PAYMENTREQUEST_0_DESC", PaymentDescription) '
NVP.Add("PAYMENTREQUEST_0_SELLERPAYPALACCOUNTID", "email1#address.com") ' ## PayPal e-mail Of first receiver
NVP.Add("PAYMENTREQUEST_0_PAYMENTREQUESTID", "CIYP CART1") ' PAYMENTREQUEST_0_PAYMENTREQUESTID = CART1 '## unique ID Of first payment – End primary level information For first payment
NVP.Add("L_PAYMENTREQUEST_0_NAME0", "Super Sub CIYP") ' L_PAYMENTREQUEST_0_NAME0 = Super Sub '## Start secondary level information For first payment first item
NVP.Add("L_PAYMENTREQUEST_0_NUMBER0", "SS - 101") '
NVP.Add("L_PAYMENTREQUEST_0_QTY0", "1") '
NVP.Add("L_PAYMENTREQUEST_0_AMT0", "125")
NVP.Add("L_PAYMENTREQUEST_0_TAXAMT0", "15") ' ## End secondary level information For first payment first item
NVP.Add("L_PAYMENTREQUEST_0_NAME1", "Classic Wine Example") ' L_PAYMENTREQUEST_0_NAME1 = EXAMPLE Classic Wine '## Start secondary level information For first payment second item
NVP.Add("L_PAYMENTREQUEST_0_QTY1", "1") '
NVP.Add("L_PAYMENTREQUEST_0_AMT1", "100") '
NVP.Add("L_PAYMENTREQUEST_0_TAXAMT1", "10") ' ## End secondary level information For first payment second item
NVP.Add("PAYMENTREQUEST_1_CURRENCYCODE", PAYMENTCURRENCYCODE) ' ## Start primary level information For second payment
NVP.Add("PAYMENTREQUEST_1_AMT", "75") ' ## total amount Of second payment
NVP.Add("PAYMENTREQUEST_1_ITEMAMT", "65") '
NVP.Add("PAYMENTREQUEST_1_TAXAMT", "10") '
NVP.Add("PAYMENTREQUEST_1_PAYMENTACTION", SALEPAYMENTACTION) '
NVP.Add("PAYMENTREQUEST_1_DESC", "Mocktail Large") '
NVP.Add("PAYMENTREQUEST_1_SELLERPAYPALACCOUNTID", "secondpayee#address.com") ' ## PayPal e-mail Of second receiver
NVP.Add("PAYMENTREQUEST_1_PAYMENTREQUESTID", "CART2") ' ## unique ID Of second payment – End primary level information For secondary payment
NVP.Add("L_PAYMENTREQUEST_1_NAME0", "Orange crush") ' ## Start secondary level information For secondary payment first item
NVP.Add("L_PAYMENTREQUEST_1_NUMBER0", "MC - 77") '
NVP.Add("L_PAYMENTREQUEST_1_QTY0", "1") '
NVP.Add("L_PAYMENTREQUEST_1_AMT0", "65") '
NVP.Add("L_PAYMENTREQUEST_1_TAXAMT0", "10") ' ## End secondary level information For second payment first item
''build the parameter string
Dim paramBuilder As New StringBuilder
For Each kv As KeyValuePair(Of String, String) In NVP
Dim st As String
st = kv.Key & "=" & HttpUtility.UrlEncode(kv.Value) & "&"
paramBuilder.Append(st)
Next
Dim param As String
param = paramBuilder.ToString
param = param.Substring(0, param.Length - 1) ''remove the last '&'
''Create web request and web response objects, make sure you using the correct server (sandbox/live)
Dim wrWebRequest As Net.HttpWebRequest = DirectCast(Net.WebRequest.Create(paypalApiServerUrl), Net.HttpWebRequest)
wrWebRequest.Method = "POST"
Dim requestWriter As New IO.StreamWriter(wrWebRequest.GetRequestStream())
requestWriter.Write(param)
requestWriter.Close()
'' Get the responseReader
Dim responseReader As IO.StreamReader
responseReader = New IO.StreamReader(wrWebRequest.GetResponse().GetResponseStream())
''read the response
Dim responseData As String
responseData = responseReader.ReadToEnd()
responseReader.Close()
''url-decode the results
Dim result As String
result = HttpUtility.UrlDecode(responseData)
Dim formattedResult As String
formattedResult = "Request on " & paypalApiServerUrl & vbCrLf &
HttpUtility.UrlDecode(param.Replace("&", vbCrLf & " ")) & vbCrLf & vbCrLf &
"Result:" & vbCrLf & HttpUtility.UrlDecode(responseData.Replace("&", vbCrLf & " ")) & vbCrLf & vbCrLf &
"--------------------------------------" & vbCrLf
''show the results
Console.WriteLine(formattedResult)
Response.Write(formattedResult)
MSG.Text = formattedResult
End Sub
What I came up with is not working,
Message: The request was aborted: Could not create SSL/TLS secure channel.
Found these resources which helped shed some light on the subject
http://brad.w3portals.com/2008/03/paypal-nvp-api-example-for-vbnet-aspnet.html
How to create Encrypted PayNow button "on the fly" for Third-party customers, using Paypal NVP API?
https://www.paypal.com/businessprofile/mytools/apiaccess/firstparty/signature
For name value pair format, the values (right hand side) should be URL encoded, and the pairs should be separated by ampersands (&)
You can have a function that builds the request string text out of an array or dictionary
Are you using a valid USER/PWD/Signature from the profile of a Sandbox Business account at https://www.paypal.com/signin?intent=developer&returnUri=https%3A%2F%2Fdeveloper.paypal.com%2Fdeveloper%2Faccounts%2F ?
An SSL/TLS error may be due a lack of TLSv1.2 support on the server or framework environment, among other possible causes like not trusting the root CA issuer of the SSL certificate of the api-3t.paypal.com server it's connecting to

Why do i get error message when i loop

' the loop statement
do while messagessent < messages submitted
messagessent = messagesent + 1
Dim client = New RestClient("https://api.infobip.com/sms/1/text/multi")
foneno = trim(foneno.Replace(",",""","""))
Dim request = New RestRequest(Method.POST)
request.AddHeader("accept", "application/json")
request.AddHeader("content-type", "application/json")
request.AddHeader("authorization", "Basic NutrtryoYW5nZW1lMUE=") 'base64 of usename and password
request.AddParameter("application/json","{""messages"":[{""from"":""" + senderid + """,""to"":["""& mobileno &""" ],""text"":""" + message + """}]}",ParameterType.RequestBody)
Dim eresponse As IRestResponse = client.Execute(request)
loop
I'm not sure what other issues the code has but from what i can see here you have two obvious errors.
The loop conditional statement uses a variable messages submitted i doubt this is valid.
You are processing a variable foneno and using a different one in the code below it mobileno. obviously one of these 2 haven't been declared.

How to send multiple emails with ASP.NET VB.net

How do I set the code below to generate multiple emails like with a reminder every 15 minutes? Thank you for any guidance.
Private Sub SendEmail(ByVal pharmEmail As String, ByVal backupEmail As String)
Dim smtpClient As New System.Net.Mail.SmtpClient()
Dim message As New System.Net.Mail.MailMessage()
Try
Dim fromAddress As New System.Net.Mail.MailAddress(WebConfigurationManager.AppSettings("EmailFromAddr"), WebConfigurationManager.AppSettings("EmailFromName"))
message.From = fromAddress
message.To.Add(pharmEmail)
message.Subject = WebConfigurationManager.AppSettings("EmailSubject")
message.Priority = Net.Mail.MailPriority.High
If (WebConfigurationManager.AppSettings("backupEnabled") = True) Then
message.CC.Add(backupEmail)
End If
message.IsBodyHtml = True
Dim orderURL As New HyperLink
orderURL.Text = "here"
orderURL.NavigateUrl = "http://" & WebConfigurationManager.AppSettings("ServerName") & "/User/ReviewOrder.aspx?orderID=" & webOrderID
message.Body = "An order was created using the account of " + Profile.FirstName.ToString() + " " + Profile.LastName.ToString() + ". " + WebConfigurationManager.AppSettings("EmailBody") + "<a href='" + orderURL.NavigateUrl + "'>here.</a>"
'message.Body = WebConfigurationManager.AppSettings("EmailBody") & " " & orderURL.
smtpClient.Send(message)
Catch ex As Exception
ErrorHandler.WriteError(ex.ToString)
Throw ex
End Try
I agree with comments on the scheduler. If you don't like that you can create a windows service that does this. This will solve if you want to fire the routine every X minutes.
You don't have enough code here to send out emails, so you have to wrap this with some logic that fires the routine with the email information you want. More than likely, this is stored in a database (recipients, email) or some other persistent store.
I do caution the idea of sending reminders every 15 minutes to the same people, as you are more than likely to piss them off (unless that is your intent?).
Thank you all for you contributions. I have decided to create a SSIS package with a SQL and Send Email tasks. The SQL task check for new orders placed and the Send Email task sends reminder to users in a scheduled time.

I'm getting incorrect 'MembershipCreateStatus' data [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have the following code which creates a memebrship user, then calls other methods to insert the users other info into my SQL DB. The user is getting created. The info is getting into my database. Everything is working like it should, but for some reason, Rather then sending a success message to my Literal0.text, it always says "There is already a user with this email address.", even after the user is successfully created.I even added a check for Session("Created") to keep the code from running twice, still no luck. It works fine, just gives the wrong message at the end.
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Not Session("Created") = "True" Then
Literal0.Text = ""
Dim FName As String = FNameBox.Text.Replace("'", "*1*").Replace("""", "*2*").Replace(" ", "")
Dim LName As String = LNameBox.Text.Replace("'", "*1*").Replace("""", "*2*").Replace(" ", "")
Username = FName + "." + LName
Dim SecretQ As String = "Please use the Contact Us page to request a reset password"
Dim SecretA As String = "ergwergkqejfqeoufwqeofiheowfqpkoadmvnwo"
Dim psw As Int32 = (TimeOfDay.Hour * TimeOfDay.Minute) * 863490
Dim firstsix As String = psw.ToString().Substring(0, 6)
password = FNameBox.Text.Replace("'", "*1*").Replace("""", "*2*").Replace(" ", "") + firstsix + "!"
Dim createStatus As MembershipCreateStatus
Dim newUser As MembershipUser = _
Membership.CreateUser(Username, password, _
Email.Text, SecretQ, _
SecretA, True, _
createStatus)
Select Case createStatus
Case MembershipCreateStatus.Success
Session("Created") = "True"
If Not String.IsNullOrEmpty(BlogSettings.Instance.SelfRegistrationInitialRole) Then
Dim role As String = Roles.GetAllRoles().FirstOrDefault(Function(r) r.Equals(BlogSettings.Instance.SelfRegistrationInitialRole, StringComparison.OrdinalIgnoreCase))
If Not String.IsNullOrEmpty(role) Then
Roles.AddUsersToRoles(New String() {Username}, New String() {role})
End If
End If
Dim pf = AuthorProfile.GetProfile(Username)
pf = New AuthorProfile(Username)
pf.DisplayName = Username
pf.EmailAddress = Email.Text
pf.FirstName = FNameBox.Text.Replace("'", "*1*").Replace("""", "*2*").Replace(" ", "")
pf.LastName = LNameBox.Text.Replace("'", "*1*").Replace("""", "*2*").Replace(" ", "")
pf.[Private] = True
pf.Save()
Literal0.Text = ""
AddUser()
Exit Select
Case MembershipCreateStatus.DuplicateUserName
Literal0.Text = "There is already a user with this username."
Exit Select
Case MembershipCreateStatus.DuplicateEmail
Literal0.Text = "There is already a user with this email address."
Exit Select
Case MembershipCreateStatus.InvalidEmail
Literal0.Text = "There email address you provided in invalid."
Exit Select
Case MembershipCreateStatus.InvalidAnswer
Literal0.Text = "There security answer was invalid."
Exit Select
Case MembershipCreateStatus.InvalidPassword
Literal0.Text = "The password you provided is invalid. It must be seven characters long and have at least one non-alphanumeric character."
Exit Select
Case Else
Literal0.Text = "There was an unknown error; the user account was NOT created."
Exit Select
End Select
End If
End Sub
I would suggest to check the code from the parts below:
please make some break points to the application, we should check if every time the debug point will go to the case below:
Case MembershipCreateStatus.DuplicateEmail
Literal0.Text = "There is already a user with this email address."
Exit Select
and please make sure the email do not exist in the DataTable.
For more information about the MembershipCreateStatus, please refer to the link below:
http://msdn.microsoft.com/en-us/library/system.web.security.membershipcreatestatus.aspx
Hope it's useful for you.

How to write response into Buffer instead of rendering on Screen?

I am developing app where I need to capture an Information from Webpage after giving credentials automatically. Some how I managed to do Automatic login and redirection of page. Here is my code :
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://abcd.com.au/categories/A_dfn/sdf");
HttpWebResponse res = req.GetResponse() as HttpWebResponse;
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[10000];
Stream resStream = res.GetResponseStream();
string s = null;
int c = 0;
do
{
c = resStream.Read(buf, 0, buf.Length);
if (c != 0) {
s = ASCIIEncoding.ASCII.GetString(buf, 0, c);
sb.Append(s);
}
} while (c > 0);
string oldhead = "class=\"login_button\">";
string newhead = "class=\"login_button\"> <script type=\"text/javascript\">document.getElementById('btn').click()</script>";
sb.Replace(oldhead, newhead);
string oldbtn = "value=\"Submit\"";
string newbtn = "value=\"Submit\" id=\"btn\" ";
sb.Replace(oldbtn, newbtn);
string oldAction = "<form action=\"/login\" method=\"post\">";
string newAction = "<form action=\"https://abcd.com.au/login?orig_req_url=%2Fcategories/A_dfn/sdf\" method=\"post\">";
sb.Replace(oldAction, newAction);
string oldUsername = "<input id=\"login_email\" type=\"text\" name=\"user[email_address]\" class=\"textBox\" value=\"\">";
string newUserName = "<input id=\"login_email\" type=\"text\" name=\"user[email_address]\" class=\"textBox\" value=\"abc#xyz.com.au\">";
sb.Replace(oldUsername, newUserName);
string oldPass = "<input id=\"login_password\" type=\"password\" name=\"user[password]\" class=\"textBox\" value=\"\">";
string newPass = "<input id=\"login_password\" type=\"password\" name=\"user[password]\" class=\"textBox\" value=\"abc\">";
sb.Replace(oldPass,newPass);
Response.Write(sb);
This is show me expected output as I want by rendering page(Response.write(sb)). But, now I want to do same thing without redirecting to "https://abcd.com.au/login?orig_req_url=%2Fcategories/A_dfn/sdf" and want to do more stuff on this. I expect to get output of Response.Write(sb) in some buffer. Is it possible to do?
Here is example, that explains exactly what I want to do.
I am looking for an product's qty say name : Screw 15mm, this resides in page https://abcd.com.au/%2Fcategories/A_dfn/sdf.
So, I am requesting this url first, but as need login to access that page, its redirecting me to login page, filling username and password, pressing login button by using javascript,and then redirected to Originally Requested page. And on this page I want to find for that product, and return information to my web app.
All this I want to do without showing to user.
I just want to show retrieved information.
Thanks.
What you are looking for is a persisted session. Your approach towards this problem is incorrect. You are triggering the submit on the client-side. What you are trying to achieve should be done on the server-side.
The key to your scenario is to persist (store) the session & cookies set by the login page; then before your next request for the product info, inject the credential into the requesting webRequest.
Use the WebRequest object to load the login page.
Store any info (cookies) sent by the login page Response header.
create a new WebRequest object with the provided Response header, inject in userid/password.
Store any credentials returned by the Response.
Proceed to request for the quote info.
There is no generic way to do this without knowing the website you are trying to screen-scrap from. But the general step is as above. Basically, you need to create a custom class for this.
Also, you need HTMLAgilityPack to parse the HTML nodes. It is the correct method.
EDIT: Added my codes. Just so happen that I've created this class before sometime ago. So, you're in luck. However, you will need HTMLAgilityPack installed & referenced to use it. You can download HAP at: http://htmlagilitypack.codeplex.com/ If you want to do any serious screen-scraping, HAP is the de-facto standard.
Public Class clsBrowserSession
'=================================================================================================================================
'This is a special Browser Post class
' Instead of just POST to a URL as per the clsWeb.fnsPostResponse()
' clsBrowserSession allows us to LOAD a page first, persist all the cookies and variables, and then only POST to the target URL.
' The reason is that some program will drop (lets say) a SessionID as an input when you first load the page.
' and when you post, without the SessionID (variable), it will reject the POST. Thus clsBrowserSession can solve this problem.
'=================================================================================================================================
' USAGE:
' Dim voBrowserSession As New clsBrowserSession
' voBrowserSession.sbLoadPage("https://xxx.yyy.net.my/publicncdenq/index.htm")
' voBrowserSession.proFormElements("UserID") = "myID"
' voBrowserSession.proFormElements("Password") = "myPassword"
' Dim vsResponseHTML As String = voBrowserSession.Post("https://xxx.yyy.net.my/publicncdenq/index.htm")
Private vbIsPostingInProgress As Boolean
Public voCookies As System.Net.CookieCollection
Public proHTMLDoc As HtmlAgilityPack.HtmlDocument
Public proFormElements As clsFormElementCollection
Public Sub sbLoadPage(pvsURL As String)
vbIsPostingInProgress = False
fnoCreateWebRequestObject().Load(pvsURL)
End Sub
Public Function Post(pvsURL As String) As String
vbIsPostingInProgress = True
fnoCreateWebRequestObject().Load(pvsURL, "POST")
Return proHTMLDoc.DocumentNode.InnerHtml
End Function
Private Function fnoCreateWebRequestObject() As HtmlAgilityPack.HtmlWeb
Dim voWeb As New HtmlAgilityPack.HtmlWeb
voWeb.UseCookies = True
voWeb.PreRequest = New HtmlAgilityPack.HtmlWeb.PreRequestHandler(AddressOf event_OnPreRequest)
voWeb.PostResponse = New HtmlAgilityPack.HtmlWeb.PostResponseHandler(AddressOf event_OnAfterResponse)
voWeb.PreHandleDocument = New HtmlAgilityPack.HtmlWeb.PreHandleDocumentHandler(AddressOf event_OnPreHandleDocument)
Return voWeb
End Function
Private Sub sbAddPostDataTo(pvoRequest As Net.HttpWebRequest)
Dim vsPayload As String = proFormElements.fnsAssemblePostPayload()
Dim vabyteBuffer As Byte() = Text.Encoding.UTF8.GetBytes(vsPayload.ToCharArray())
pvoRequest.ContentLength = vabyteBuffer.Length
pvoRequest.ContentType = "application/x-www-form-urlencoded"
pvoRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11"
pvoRequest.GetRequestStream().Write(vabyteBuffer, 0, vabyteBuffer.Length)
End Sub
Private Sub sbAddvoCookiesTo(pvoRequest As Net.HttpWebRequest)
If (Not IsNothing(voCookies)) Then
If voCookies.Count > 0 Then pvoRequest.CookieContainer.Add(voCookies)
End If
End Sub
Private Sub sbSaveCookiesFrom(pvoResponse As Net.HttpWebResponse)
If pvoResponse.Cookies.Count > 0 Then
If IsNothing(voCookies) Then voCookies = New Net.CookieCollection
voCookies.Add(pvoResponse.Cookies)
End If
End Sub
Private Sub sbSaveHtmlDocument(pvoHTMLDocument As HtmlAgilityPack.HtmlDocument)
proHTMLDoc = pvoHTMLDocument
proFormElements = New clsFormElementCollection(proHTMLDoc)
End Sub
Protected Function event_OnPreRequest(pvoRequest As Net.HttpWebRequest) As Boolean
sbAddvoCookiesTo(pvoRequest)
If vbIsPostingInProgress Then sbAddPostDataTo(pvoRequest)
Return True
End Function
Protected Sub event_OnAfterResponse(pvoRequest As System.Net.HttpWebRequest, pvoResponse As Net.HttpWebResponse)
sbSaveCookiesFrom(pvoResponse)
End Sub
Protected Sub event_OnPreHandleDocument(pvoHTMLDocument As HtmlAgilityPack.HtmlDocument)
sbSaveHtmlDocument(pvoHTMLDocument)
End Sub
'-----------------------------------------------------------------------------------------------------
'Form Elements class
' Note: This element class will only capture (any) INPUT elements only, which should be enough
' for most cases. It can be easily modified to add other SELECT, TEXTAREA, etc voInputs
'-----------------------------------------------------------------------------------------------------
Public Class clsFormElementCollection
Inherits Dictionary(Of String, String)
Public Sub New(htmlDoc As HtmlAgilityPack.HtmlDocument)
Dim voInputs As Collections.Generic.IEnumerable(Of HtmlAgilityPack.HtmlNode) = htmlDoc.DocumentNode.Descendants("input")
For Each voInput As HtmlAgilityPack.HtmlNode In voInputs
Dim vsName = voInput.GetAttributeValue("name", "undefined")
Dim vsValue = voInput.GetAttributeValue("value", "")
If vsName <> "undefined" Then Add(vsName, vsValue)
Next
End Sub
Public Function fnsAssemblePostPayload() As String
Dim sb As New Text.StringBuilder
For Each voKeyValuePair In Me
Dim vsValue = System.Web.HttpUtility.UrlEncode(voKeyValuePair.Value)
sb.Append("&" & voKeyValuePair.Key & "=" & vsValue)
Next
Return sb.ToString.Substring(1)
End Function
End Class
End Class
Just make the above into a class object and instantiate it. The usage example is in the comment. You want the vsResponseHTML string.

Resources