Using the following function:
Public Sub SendMail(ByVal SendFrom As String, ByVal SendTo As String, ByVal Subject As String, ByVal Body As String)
Dim client As New SmtpClient
Dim message As New MailMessage
message.Body = Body
message.Subject = Subject
message.From = New MailAddress(SendFrom)
message.To.Add(New MailAddress(SendTo))
client.Port = "25"
client.Host = "smtp.myserver.com"
client.Send(message)
End Sub
I call it with
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
Dim iandamsb As New StringBuilder
iandamsb.AppendLine("Please make the following changes:")
iandamsb.AppendLine("")
iandamsb.AppendLine("Current name:" & txtCurrentName.Text)
iandamsb.AppendLine("New name:" & txtNewName.Text)
iandamsb.AppendLine("New username:" & txtNewUsername.Text)
iandamsb.AppendLine("Applications:" & txtOtherApplications.Text)
Dim iandambody As String = iandamsb.ToString
SendMail(txtRequesterEmail.Text, "ayockel#mydomain.com", "Name Change Request - " & txtCurrentName.Text, iandambody)
End Sub
It works just fine, however it is sending two emails instead of one. Can anyone figure out why it's sending a duplicate?
I would venture to guess that you have the button click event bound twice: once through an OnClick attribute in the markup:
<asp:Button OnClick="btnSubmit_Click" runat="server" ... />
and then again through the code-behind via Handles:
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs)
Handles btnSubmit.Click
I would remove one of them if that's the case. I would keep the latter so you know that the btnSubmit_Click event is properly wired at compile time.
A discussion of this issue.
Related
I am trying to grab an argument added to an asp:button in code behind, but getting error:
Unable to cast object of type 'System.EventArgs' to type 'System.Web.UI.WebControls.CommandEventArgs'
This button is part of a normal form, not a gridview, etc..
What might I be doing wrong? Regards.
<form><asp:Button ID="btnPrint" runat="server" Text="Print" CommandArgument="" /></form>
Imports System.Web
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim String AS String = "MyValue"
btnPrint.CommandArgument = String
End Sub
Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As CommandEventArgs) Handles btnPrint.Click
Dim ID as String = e.CommandArgument.toString
'Have also tried
'Dim btn As Button = sender
'Dim ID As String = btn.CommandArgument
Response.Redirect("Print.aspx?tid=" & ID)
End Sub
You just need to update btnPrint_Click to handle the Command event instead of "Click":
Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As CommandEventArgs) Handles btnPrint.Command
My ASP button click events look like this:
Private Sub SearchASPxButton_Click(sender As Object, e As EventArgs) Handles SearchASPxButton.Click
Notice the second parameter is of type System.EventArgs. Did you change the type of the automatically generated click event? Or did you create this manually yourself?
I am a total beginner at VB.NET so you may need to bear with me but I need to edit this code behind so that a null value is passed to my database for the 'imageurl' field. The front end is a web form where a user can enter details of a book, with the option of uploading a book cover.
I want to change my code so that if the file upload dialog does not fulfil hasFile, the GUID string generated in the database will be a NULL value (this is so I can have a 'no image available' image using the NullImageUrl property in ASP.)
This is what I've tried to implement so far, but intellisense is telling me that "Value of type String cannot be converted to 'System.GUID'.
Code Behind:
Imports System.Data.OleDb
Partial Public Class addBook
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub btn_submission_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btn_submission.Click
Dim noFile As String = Nothing
Dim myGUID = Guid.NewGuid()
Dim newFileName As String = myGUID.ToString() & ".jpg"
Dim fileLocationOnServerHardDisk = Request.MapPath("img/thumb") & "/" & newFileName
If fu_picture.HasFile Then
fu_picture.SaveAs(fileLocationOnServerHardDisk)
Else
myGUID = noFile
End If
Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim SqlString As String = "Insert into booklist(Title,Author,PublicationDate,Pages,Publisher,Blurb,imgurl,AverageRating)
Values (#f1,#f2,#f3,#f4,#f5,#f6,#f7,#f8)"
Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#f1", tb_booktitle.Text)
cmd.Parameters.AddWithValue("#f2", tb_bookauthor.Text)
cmd.Parameters.AddWithValue("#f3", tb_bookpubyear.Text)
cmd.Parameters.AddWithValue("#f4", tb_bookpages.Text)
cmd.Parameters.AddWithValue("#f5", tb_publisher.Text)
cmd.Parameters.AddWithValue("#f6", tb_blurb.Text)
cmd.Parameters.AddWithValue("#f7", "img/thumb/" & newFileName)
cmd.Parameters.AddWithValue("#f8", rbl_Stars.SelectedValue)
oleDbConn.Open()
cmd.ExecuteNonQuery()
System.Threading.Thread.Sleep("2000")
Response.Redirect("~/addedrecord.aspx")
End Sub
Protected Sub rbl_Stars_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles rbl_Stars.SelectedIndexChanged
End Sub
End Class
Please tell me if I'm completely wrong in my line of thinking!
EDIT: At this present moment, even if a file is not uploaded, a guid string + jpg suffix are generated in the database table even if the image itself doesn't exist
You should pass DBNull.Value to your db if you fail the requirement
cmd.Parameters.AddWithValue("#f7", _
if(fu_picture.HasFile, "img/thumb/" & newFileName, DbNull.Value)
The ternary operator allows you to test the flag HasFile just when you create the parameter.
If it is false you set the parameter value to DBNull.Value. If HasFile is true you can build the correct path to your imagefile. Of course this removes the necessity to assign Nothing to myGuid in the code before.
I have created test project to send message via google talk using Jabber library. As I already have test project that can send message successfully using agsXMPP, I want to imitate this project to use jabber library instead. However, there is no message sent even though the code run pass sending message command without any error. It seems that the password has not even been checked as it didn't enter OnAuthError event.
My test project is ASP.NET Web application project using VB.NET language. There are 4 textboxes to fill in: sender account (txt_Sender), sender's password (txt_Password), message to be sent (txt_Message) and receiver account (txt_Receiver) and also 1 button for sending the message (btn_Send). I test by using my email account (xxx1#gmail.com) and send message to my friend (xxx2#gmail.com). Here are my VB code
Imports jabber
Imports jabber.client
Imports Microsoft.Win32
Imports System.Threading
Imports jabber.protocol.client
Imports jabber.connection
Public Class TestSendMsg
Inherits System.Web.UI.Page
Public done As ManualResetEvent
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
done = New ManualResetEvent(False)
End Sub
Private Sub btn_Send_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_Send.Click
Dim jcSender As JabberClient = New JabberClient()
Dim jidSender As New jabber.JID(txt_Sender.Text.Trim)
With jcSender
.User = jidSender.User
.Password = txt_Password.Text.Trim
.Server = jidSender.Server
.AutoReconnect = True
.AutoRoster = True
End With
With jcSender
Try
AddHandler .OnAuthenticate, New bedrock.ObjectHandler(AddressOf j_OnAuthenticate)
'AddHandler .OnAuthenticate, AddressOf j_OnAuthenticate
AddHandler .OnPresence, AddressOf j_OnPresence
AddHandler .OnBeforePresenceOut, AddressOf j_OnBeforePresenceOut
AddHandler .OnAuthError, AddressOf j_OnAuthError
AddHandler .OnAfterPresenceOut, AddressOf j_OnAfterPresenceOut
.Connect()
.Login()
.IsAuthenticated = True
.Message(txt_Reciever.Text.Trim, txt_Message.Text.Trim)
Catch ex As Exception
MsgBox(ex.Message)
End Try
.Close()
.Dispose()
End With
End Sub
Private Sub j_OnAfterPresenceOut(ByVal sender As Object, ByVal pres As Presence)
'Dim j As JabberClient = CType(sender, JabberClient)
'j.Message(TARGET, "Registered: " & iq.BaseURI)
'done.Set()
End Sub
Private Sub j_OnAuthError(ByVal sender As Object, ByVal pres As Presence)
'Dim j As JabberClient = CType(sender, JabberClient)
'j.Message(TARGET, "Registered: " & iq.BaseURI)
'done.Set()
End Sub
Private Sub j_OnBeforePresenceOut(ByVal sender As Object, ByVal pres As Presence)
'Dim j As JabberClient = CType(sender, JabberClient)
'j.Message(TARGET, "Registered: " & iq.BaseURI)
'done.Set()
End Sub
Private Sub j_OnPresence(ByVal sender As Object, ByVal pres As Presence)
'Dim j As JabberClient = CType(sender, JabberClient)
'j.Message(TARGET, "Presence: " & pres.BaseURI)
'done.Set()
End Sub
Private Sub j_OnAuthenticate(ByVal sender As Object)
' Sender is always the JabberClient.
Dim j As JabberClient = CType(sender, JabberClient)
j.Message(txt_Reciever.Text.Trim, "Test OnAuthenticate")
' Finished sending. Shut down.
done.Set()
End Sub
End Class
You need to wait for OnAuthenticate before sending your message.
Im trying to send a Docx file via this form that I made, the email sends fine.
but the docx file gets back corrupted..
this is my backgroudn code:
'Add the namespace for the email-related classes
Imports System.Net.Mail
Partial Class SendAttachment
Inherits System.Web.UI.Page
Protected Sub SendEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SendEmail.Click
'Make sure a file has been uploaded
If String.IsNullOrEmpty(AttachmentFile.FileName) OrElse AttachmentFile.PostedFile Is Nothing Then
Throw New ApplicationException("Egad, a file wasn't uploaded... you should probably use more graceful error handling than this, though...")
End If
' UPDATE THIS VALUE TO YOUR EMAIL ADDRESS
Const ToAddress As String = "pelleg#shakuff.co.il"
'(1) Create the MailMessage instance
Dim mm As New MailMessage(UsersEmail.Text, ToAddress)
'(2) Assign the MailMessage's properties
mm.Subject = "שלוחת קורות חיים"
mm.Body = Body.Text
mm.IsBodyHtml = False
'Attach the file
mm.Attachments.Add(New Attachment(AttachmentFile.PostedFile.InputStream, AttachmentFile.FileName))
'(3) Create the SmtpClient object
Dim smtp As New SmtpClient
'(4) Send the MailMessage (will use the Web.config settings)
smtp.Send(mm)
'Show the EmailSentForm Panel and hide the EmailForm Panel
EmailSentForm.Visible = True
EmailForm.Visible = False
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
'On the first page load, hide the EmailSentForm Panel
EmailSentForm.Visible = False
End If
End Sub
End Class
its the sendemail.aspx.vb file.
any suggestions?
totally off the top of my head, but try setting:
AttachmentFile.PostedFile.InputStream.Position = 0
before you call:
'Attach the file mm.Attachments.Add(New Attachment(AttachmentFile.PostedFile.InputStream, AttachmentFile.FileName))
i have a web application for video uploading,In that i want to show the video in the link click.i wrote a function for to show the video.i want to pass the id of video into the function .How can i Do that?
Can any one help Me?
This is my code
Private Function
GetSpecificVideo(ByVal i As Object) As
DataTable
'pass the id of the video
Dim connectionString As String =
ConfigurationManager.ConnectionStrings("UploadConnectionString")
.ConnectionString
Dim adapter As New SqlDataAdapter("SELECT FileName,
FileID,FilePath " + "FROM FileM WHERE
FileID = #FileID", connectionString)
adapter.SelectCommand.Parameters.Add("#FileID",
SqlDbType.Int).Value = DirectCast(i, Integer)
Dim table As New DataTable()
adapter.Fill(table)
Return table
End Function
Protected Sub ButtonShowVideo_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles ButtonShowVideo.Click
Repeater1.DataSource = GetSpecificVideo(****here i want to get the ID****)
'the video id (2 is example)
Repeater1.DataBind()
End Sub
of the many ways one is to set CommandArgument for the link (or rather button as your code seems).
ASPX:
<ItemTemplate>
<asp:LinkButton ID="lnkVideo" runat="server"
CommandArgument='<%# Eval("VideoID")%>'
OnClick="ButtonShowVideo_Click">Watch Video</asp:LinkButton>
</ItemTemplate>
Code:
private sub void GetVideos()
'GET VIDEO(S)
'CREATE LINKS OR IF IN GRID GET LINKS AND SET COMMAND ARGUMENT FOR IT
lnk1.CommandArgument = ID_OF_VIDEO
end sub
now handle click:
Protected Sub ButtonShowVideo_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles ButtonShowVideo.Click
var btn = sender as Button 'or Link or LinkButton
if(btn is not null) then
if(NOT string.IsNullOrEmpty(btn.CommandArgument)) then
var vid = Convert.ToInt32(btn.CommandArgument)
Repeater1.DataSource = GetSpecificVideo(vid)
Repeater1.DataBind()
end if
end if
End Sub