execute code on load in vb.net aspx page - asp.net

I appreciate help for this issue which stoled a lot of hours.
I have this code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Label1.Text = "924 695 302"
Label2.Text = "690 142 449"
Dim ipvisitante = Request.ServerVariables("remote_addr")
Dim hoje = DateTime.Now
Dim informacao = ipvisitante & " --- " & hoje
'Send e-mail
Dim strFrom = "fernandopessoa#fpessoa.net" ''IMPORTANT: This must be same as your smtp authentication address.
Dim strTo = "francopessoa.espana#hotmail.com"
Dim MailMsg As New MailMessage(New MailAddress(strFrom.Trim()), New MailAddress(strTo))
MailMsg.BodyEncoding = Encoding.Default
MailMsg.Subject = "This is a test"
MailMsg.Body = "This is a sample message using SMTP authentication"
MailMsg.Priority = MailPriority.High
MailMsg.IsBodyHtml = True
'Smtpclient to send the mail message
Dim SmtpMail As New SmtpClient
Dim basicAuthenticationInfo As New Net.NetworkCredential("fernandopessoa#fpessoa.net", "---------")
''IMPORANT: Your smtp login email MUST be same as your FROM address.
SmtpMail.Host = "mail.fpessoa.net"
SmtpMail.UseDefaultCredentials = False
SmtpMail.Credentials = basicAuthenticationInfo
MsgBox("O ficheiro existe", MsgBoxStyle.Information, "SIM")
'Write to txt File
FileOpen(1, "visitas.txt", OpenMode.Append)
WriteLine(1, informacao)
FileClose()
End Sub
Now, when the page Loads, the text apears in the Labels.
Surprisingly, it doesn't execute the rest of the code, Display Msgbox, Write to the .txt File and send the e-mail.
Can anyone give me a clue of what's going wrong with my code?
Thanks in advance.

The code does execute... it runs on the Web Server. It does not run in the client's web browser, and never will.
That explains the MsBox() and file, though the web server may also be getting hung up waiting for someone to click "Okay" on a MsgBox no one will ever see. For the e-mail, you never call SmtpMail.Send(MailMsg)
While I'm here, that file code is using an antique api.
It sounds like you need a quick primer on how this all works, so here is what happens step by step:
User clicks a link to your page or types your page address in their address bar.
The browser sends an HTTP request to your server.
Your server receives the request, creates a new instance of your page class in a worker thread.
Code runs in your page class for ALL phases of the ASP.Net Page Lifecycle .
The ASP.Net runtime uses your page class instance to render an HTTP response (usually in html) and send it to the browser.
Your page class instance is destroyed.
The browser receives the response, parses a new Document Object Model (DOM), and renders that DOM to the display.
The user sees and interacts with your page, causing a post-back.
Go to step 2, taking special note of the "new instance" phrase when you reach step 3.

Related

"Validation of viewstate MAC failed" only when posting back from a mobile browser that has been idle for sometime

I know that this question has been asked frequently on StackOverflow but my case is a bit different. I checked all the answers related to this issue and none solved my problem as in my case it only happens with browsers on mobile devices.
I only get the "Validation of ViewState MAC failed" error when posting back from a mobile browser that has been left open for some time. The error never appears when submitting a form from a computer browser. It neither appears when submitting from a mobile browser most of the time. It only appears when I open a mobile tab that was already submitted from some time and click the submit button again.
However, It happens all the time as well when I close my browser (so that it is not running in the mobile background), open it again and re-submit the form. I guess this is the main problem behind this error (re-launching the browser is causing page-reload on mobile before clicking on anything).
I tried the below solutions and none of them worked:
Manually set MachineKey to my web.config
Use aspnet_regiis utility to run the managed application where machine keys will be persisted.
Solutions proposed in this article
set LoadUserProfile = True in the application pool
Set the SessionTimeout = 0 in IIS application pool.
Secured my cookies over http.
Note: I know that setting enableViewStateMac="false" in my web.config will solve my problem, but I really don't wish to do so to avoid security depreciation in my application.
After a couple of tests, I noticed that the error only generates when the mobile browser force-reload/relaunch the page. For example, if I re-submit the form that has been already submitted from a mobile, most of the times it does not generate an error. However, sometimes, when I open the browser on the mobile, it force-reload/relaunches the page before I click on anything. Now when I click on the submit button, the error appears.
Possibly, this force-reload/relaunch is causing this error since the ViewState is being altered.
Another possibility is that the mobile is expiring the sessions even though I've set the sessions to not expire in my IIS.
Yet, another possibility would be that the mobile does not allow the browser to run in the background resulting in force-reload to re-construct the page when the user opens the browser again.
I am using the below code in my application:
Partial Class MasterPage
Inherits System.Web.UI.MasterPage
Private Const AntiXsrfTokenKey As String = "__AntiXsrfToken"
Private Const AntiXsrfUserNameKey As String = "__AntiXsrfUserName"
Private _antiXsrfTokenValue As String
Protected Sub Page_Init(sender As Object, e As EventArgs)
' The code below helps to protect against XSRF attacks
Dim requestCookie = Request.Cookies(AntiXsrfTokenKey)
Dim requestCookieGuidValue As Guid
If requestCookie IsNot Nothing AndAlso Guid.TryParse(requestCookie.Value, requestCookieGuidValue) Then
' Use the Anti-XSRF token from the cookie
_antiXsrfTokenValue = requestCookie.Value
Page.ViewStateUserKey = _antiXsrfTokenValue
Else
' Generate a new Anti-XSRF token and save to the cookie
_antiXsrfTokenValue = Guid.NewGuid().ToString("N")
Page.ViewStateUserKey = _antiXsrfTokenValue
Dim responseCookie = New HttpCookie(AntiXsrfTokenKey) With {
.HttpOnly = True,
.Value = _antiXsrfTokenValue
}
If FormsAuthentication.RequireSSL AndAlso Request.IsSecureConnection Then
responseCookie.Secure = True
End If
Response.Cookies.[Set](responseCookie)
End If
AddHandler Page.PreLoad, AddressOf master_Page_PreLoad
End Sub
Protected Sub master_Page_PreLoad(sender As Object, e As EventArgs)
If Not IsPostBack Then
' Set Anti-XSRF token
ViewState(AntiXsrfTokenKey) = Page.ViewStateUserKey
ViewState(AntiXsrfUserNameKey) = If(Context.User.Identity.Name, [String].Empty)
Else
' Validate the Anti-XSRF token
If DirectCast(ViewState(AntiXsrfTokenKey), String) <> _antiXsrfTokenValue OrElse DirectCast(ViewState(AntiXsrfUserNameKey), String) <> (If(Context.User.Identity.Name, [String].Empty)) Then
Throw New InvalidOperationException("Validation of Anti-XSRF token failed.")
End If
End If
End Sub
Private Sub MasterPage_Load(sender As Object, e As EventArgs) Handles Me.Load
'Add Base Path and Canonical URL
Dim strBasePath = "<base href='" & AppSettings("LivePath") & "' />"
Page.Header.Controls.Add(New LiteralControl(strBasePath))
End Sub
End Class
I hope there is a solution to this since I don't want to end up setting enableViewStateMac="false" in my web.config
[Update]
Potential Solution:
My current potential solution for this is to handle the "Validation of ViewState MAC failed" error and prompt a custom message to the user explaining the form validation failure. This way security and usability is balanced.
I was inspired by this article for this likely short-lived solution.

Batch processing with Google Calendar V3 API

I've been working with the new google Calendar V3 API and I've coded all my class methods to process Adds, Updates, retrievals etc but I was wondering if there is a way to send a batch of adds + updates + deletes all at once rather than sending each request separately and possible exceeding the trans/sec threshold. I understand the .Batch method has been depreciated in V3 and I found another methodology that uses web services that will notify a client that changes are ready but I'm trying to do this from a .NET Winform application so it needs to be something initiated from the client and not dependent upon online services or a PUSH methodology.
Regards,
Kerry
I got this to work using the BatchRequest object:
Dim initializer As New BaseClientService.Initializer()
initializer.HttpClientInitializer = credential
initializer.ApplicationName = "My App"
Dim service = New CalendarService(initializer)
'fetch the calendars
Dim list = service.CalendarList.List().Execute().Items()
'get the calendar you want to work with
Dim calendar = list.First(Function(x) x.Summary = "{Calendar Name}")
Dim br As New Google.Apis.Requests.BatchRequest(service)
'make 5 events
For i = 1 To 5
'create a new event
Dim e As New [Event]
'set the event properties
e.Summary = "Test Event"
e.Description = "Test Description"
e.Location = "Test Location"
...
'make a request to insert the event
Dim ins As New InsertRequest(service, e, calendar.Id)
'queue the request
br.Queue(Of Dummy)(ins, AddressOf OnResponse)
Next
'execute the batch request
Dim t = br.ExecuteAsync()
'wait for completion
t.Wait()
For some reason, you can't have a deferred request without specifying a callback to the Queue method, and that method requires a generic type parameter. So I defined the following:
Class Dummy
End Class
Sub OnResponse(content As Dummy, err As Google.Apis.Requests.RequestError, index As Integer, message As System.Net.Http.HttpResponseMessage)
End Sub
With this in place, the batch inserts worked fine.

E-mail with no content when using the System.Threading.ThreadPool

I'm experiencing a strange behavior trying to send email using Threading.ThreadPool.
This has worked for over a year now but recently it has stated to intermittently send emails with no content. The addressees and subject are all fine, however, the rest of the email is blank. Nothing has changed code wise (apart from Windows updates to the server it runs on).
Here's the code I'm using - does anyone have a suggestion of how I might narrow down where the problem is occurring? Upon re-sending the email to someone who has claimed of receiving a blank email they get it fine - it uses the exact same code as the first one that was sent.
Sub to generate email:
Public Sub EmailConfirmation(email As String,
firstname As String,
details As String)
Try
Dim embody As String = GlobalHelper.emailBody
'static class which loads the email text at application load for use later.
'This is a point of concern because it's obviously where the embody text is
'is loaded, but the issue is intermittent and if there was a failure here surely
'it would be caught by the 'try...catch' and a log of the error created (which has
'never happened). I also ran an experiment for a while where if this string was
'empty then create a log entry. After receiving a complaint of a blank email
'no error log was found.
embody = Replace(embody, "[FirstName]", firstname)
embody = Replace(embody, "[DATA]", details)
'create the mail message
Dim mail As New MailMessage()
'set the addresses
mail.From = New MailAddress("myemail#mydomain.com", "My Display Name")
mail.To.Add(email)
mail.IsBodyHtml = True
'set the content
mail.Subject = "Email Subject!"
mail.Body = embody
AddEmailToThreadPool(mail)
Catch ex As Exception
'if there is an error it is logged here.
End Try
End Sub
Sub that adds to ThreadPool:
Private Sub AddEmailToThreadPool(email As MailMessage)
System.Threading.ThreadPool.QueueUserWorkItem(New System.Threading.WaitCallback(AddressOf sendEmail), email)
End Sub
Sub that sends email:
Private Sub sendEmail(stateinfo As Object)
Dim email As MailMessage = CType(stateinfo, MailMessage)
Try
'send the message
Dim smtp As New SmtpClient("mail.mydomain.com")
smtp.Send(email)
Catch ex As Exception
'error is logged here.
End Try
End Sub
I copied from MSDN MailMessage class
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Well, after fixing the incorrect doc type declaration I've not had a single complaint of blank emails in almost a month. I'm going to assume this fixed the problem all though I'm not certain why.
Thanks for all of your input/help.

VB.NET mailto: Run-time error '91'

Can anyone take a look at my code below and recommend how I can stop receiving the dreaded error 91. Error: Object variable or With block variable not set.
I am using the mailto: function to send an email using the native email client and populating the email w/ data from a gridview. After the error pops up, I simply click ok and the email is loaded w/ the exact data I want!
Protected Sub GridView2_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView2.SelectedIndexChanged, GridView1.SelectedIndexChanged
Dim MailFormat, Number, BodyOfEmail, FullName As String
Dim RowValue As Double
RowValue = GridView1.SelectedDataKey.Value - 1
Number = GridView1.Rows(RowValue).Cells(5).Text.ToString
FullName = GridView1.Rows(RowValue).Cells(25).Text.ToString
BodyOfEmail = “SomeTextInTheBody”
MailFormat = "mailto:" & Number & "?" & "subject= A subject here" & "&body=" & BodyOfEmail
System.Diagnostics.Process.Start(MailFormat)
End Sub
I can execute the following code from the .aspx page just fine:
a href="mailto:someone#example.com?Subject=Hello%20again"
and outlook opens without issue. It appears to only be an issue when the aspx.vb code up at the top is executed...
Thanks
<a href="mailto:xxx"/> works fine because it is executing in the user's browser, and will use the user's locally-installed interactive email application, whatever it happens to be.
Process.Start("mailto:xxx") will always fail because it is executing on the web server, which will probably not have a locally-installed interactive email application available, and even if it did, you would not be able to start it interactively on a desktop that does not exist. The fact that it happens to throw error 91 in your test environment is irrelevant. Don't do it, full stop.
What you need to do is arrange for a bit of JavaScript to execute on page render after the server-side event has completed. Something like location.href = "mailto:xxx" may do the trick. Exactly where you should insert this depends on your page design.
Alternatively, if you want to keep the email generation code entirely on the server-side, and you know that your users will always be using Outlook, you could look at calling Exchange Server directly. See here for a starting point.
Have you considered using the SmtpClient class?
Dim SmtpServer As New SmtpClient()
Dim mail As New MailMessage()
SmtpServer.Credentials = New Net.NetworkCredential("sender address", "sender password")
SmtpServer.Port = 587 'If sending from gmail...
SmtpServer.Host = "smtp.gmail.com" 'If sending from gmail...
mail = New MailMessage()
mail.From = New MailAddress("sender address")
mail.To.Add("recipient address")
mail.Subject = ""
mail.Body = ""
SmtpServer.Send(mail)

BackgroundWorker for YouTube DirectUpload in VB.NET?

I'm trying to implement a direct upload of videos on my server to YouTube. When a user adds a video, it gets copied to YouTube.
The user action of adding the video should begin the upload process, which could take a while. The form, even an asynchronous form, should not sit there and wait for this to happen. It should just begin and allow the user to move on, trusting that it is being taken care of in the background.
To allow this, I am attempting to use system.threading.backgroundworker. My hope is that the process would begin, and the web app would move on. It's not. It's hanging, whether it's an asynchronous or full postback, and waiting for the upload to finish before returning and updating the lblmsg.text.
Is there a different way I should be going about this, so the user can initiate the upload procedure and not wait around for it to complete? Here is my code so far:
Sub up_load(s As Object, e As EventArgs)
Dim worker As BackgroundWorker = New BackgroundWorker
worker.WorkerReportsProgress = True
worker.WorkerSupportsCancellation = True
AddHandler (worker.DoWork), AddressOf begin_upload
'call this and move on?
worker.RunWorkerAsync()
lblmsg.Text = "Successfully initiated upload"
End Sub
Sub begin_upload(s As Object, e As DoWorkEventArgs)
Dim request As New YouTubeRequest(settings)
Dim vidupload As New Video()
vidupload.Title = "My Big Test Movie"
vidupload.Tags.Add(New MediaCategory("Nonprofit", YouTubeNameTable.CategorySchema))
vidupload.Keywords = "church, jesus"
vidupload.Description = "See the entire video"
vidupload.YouTubeEntry.Private = False
vidupload.YouTubeEntry.setYouTubeExtension("location", "Downers Grove, IL")
vidupload.YouTubeEntry.MediaSource = New MediaFileSource("c:\users\greg\test3.asf", "video/x-ms-wmv")
Dim createdVideo As Video = Request.Upload(vidupload)
End Sub
You might want to look into the Task Parallel Library for adding multithreading to your code. Given the code that you provided:
Add this import statement
Imports System.Threading.Tasks
And replace all backgroundworker logic with this simple statement:
Dim uploadTask As Task = Task.Factory.StartNew(Sub()
Dim request As New YouTubeRequest(settings)
Dim vidupload As New Video()
vidupload.Title = "My Big Test Movie"
vidupload.Tags.Add(New MediaCategory("Nonprofit", YouTubeNameTable.CategorySchema))
vidupload.Keywords = "church, jesus"
vidupload.Description = "See the entire video"
vidupload.YouTubeEntry.Private = False
vidupload.YouTubeEntry.setYouTubeExtension("location", "Downers Grove, IL")
vidupload.YouTubeEntry.MediaSource = New MediaFileSource("c:\users\greg\test3.asf", "video/x-ms-wmv")
Dim createdVideo As Video = request.Upload(vidupload)
End Sub)
Now you have the uploadTask uploading your video in the background and your UI thread will be free to process other code. It does get a bit more complicated if you want cancellation and progress reporting, but the link at the top should get you started.

Resources