asp.net vb - docx corrupotion on email receving - asp.net

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))

Related

Failed to open connection when exporting crystal report

I'm trying to export my crystal report to pdf but keep getting the "failed to open a connection" error. It seems as if the error is happening at the CR.Export line. I've tried everything but don't know how to fix it. FYI, it's working on my development server, but when I copy it to the production server, I get the error. So it's very hard to pin point where it's occurring.
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
Try
InitializeComponent()
strPermitNo = Session("RecordID")
SpWithViewer(strPermitNo)
CrystalReportViewer2.DataBind()
Catch er As Exception
LogError(er.ToString, "PageInit-PrintPermit1.aspx")
Exit Try
Finally
End Try
End Sub
`
Protected Sub btnExport_Click(sender As Object, e As EventArgs) Handles btnExport.Click
strPermitNo = Session("RecordID")
Try
Dim CrExportOptions As ExportOptions
Dim CrDiskFileDestinationOptions As New DiskFileDestinationOptions()
Dim CrFormatTypeOptions As New PdfRtfWordFormatOptions()
CrDiskFileDestinationOptions.DiskFileName = "\\idsfmsrvr\wwwroot\FWPDFs\" & strPermitNo & ".pdf"
strAttachment = "\\idsfmsrvr\wwwroot\FWPDFs\" & strPermitNo & ".pdf"
Session("Attachment") = strAttachment
CrExportOptions = CR.ExportOptions
If True Then
CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile
CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat
CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions
CrExportOptions.FormatOptions = CrFormatTypeOptions
End If
CR.Export()
EmailPermitToApplicant()
File.Delete(strAttachment)
lblMsg.Text = "Permit has been emailed to applicant."
lblMsg.Visible = True
Catch er As Exception
LogError(er.ToString, "btnExport()-PrintPermit1.aspx")
Exit Try
Finally
connFTS.Close()
End Try`
Just a step:
Open a report first, follow this link
Export it whatever you want.
Take note: you can hide the form if you don't want to display the report.
Good Luck!

Need a 'RaiseEvent' statment to raise an event

I have a page on the website that display a client details in text boxes.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not page.IsPostBack Then
Dim dh As New Datahandler
Dim CI As ClientInfomation = dh.GETClientInfomationWithClientID(Session("ClientID"))
txtClientID.Text = Session("ClientID")
txtCompany.Text = CI.Company
txtEmail.Text = CI.Email
txtPassword.text = CI.Password
dtSubcriptionEndDate.Text = CI.SubscriptionEndDate
txtContactName.Text = CI.ContactName
txtTelephoneNum.Text = CI.Telephone.ToString()
End If
The above code works,the code gets the client data from the database in the GETClientInfomationWithClientID(Session("ClientID")) and loads the data into a class, and from the class I load the data into the text boxes.
Here is where my problem starts. A user will now change his details in the text boxes and click the 'Save changes' button invoking the butSaveChanges_Click Event.
Protected Sub butSaveChanges_Click(sender As Object, e As EventArgs) Handles butSaveChanges.Click
Dim dh As New Datahandler
Dim CI As New ClientInfomation With {.ClientID = txtClientID.Text,
.Company = txtCompany.Text,
.ContactName = txtContactName.Text,
.Email = txtEmail.Text,
.Password = txtPassword.Text,
.SubscriptionEndDate = dtSubcriptionEndDate.Text,
.Telephone = txtTelephoneNum.Text}
If dh.SaveUserProfileChanegs(CI) = True Then
ClientScript.RegisterStartupScript(Me.[GetType](), "alert", "alert('Changes has been saved')", True)
Else
ClientScript.RegisterStartupScript(Me.[GetType](), "alert", "alert('Changes could not be saved')", True)
End If
End Sub
I just wanted to load the changed text values into the class, and load the class in the SaveUserProfileChanegs(CI) function that updates the new values in the database.
When the butSaveChanges_Click event is invoked I get a "(1) : error BC32022: 'Public Event Click As EventHandler' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event."

Why is my VB.NET website not sending an email?

My code is adding a user to my database. I am trying to have my site send an email with a passcode to verify the email account is legit.
First I am trying to get it to send a basic test email. Then I plan on adding the passcode in a link to my site validating it.
My problem is my code doesn't send the basic test email.
Imports System.Data.SqlClient
Imports System.Net.Mail
Partial Class Account_Register
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
RegisterUser.ContinueDestinationPageUrl = Request.QueryString("ReturnUrl")
End Sub
Protected Sub RegisterUser_CreatedUser(ByVal sender As Object, ByVal e As EventArgs) Handles RegisterUser.CreatedUser
FormsAuthentication.SetAuthCookie(RegisterUser.UserName, False)
Dim MyMailMessage As New MailMessage()
' MyMailMessage.IsBodyHtml = True
MyMailMessage.From = New MailAddress("NAME#gmail.com")
MyMailMessage.To.Add("Name#yahoo.com")
MyMailMessage.Subject = "Email Confirmation"
MyMailMessage.Body = "TESTING"
'MyMailMessage.Body = "<html>" & RegisterUser.UserName & "Link: $" & "<br/> " & "</html>"
'Create the SMTPClient object and specify the SMTP GMail server
Dim SMTPServer As New SmtpClient("smtp.gmail.com")
SMTPServer.Port = 588
SMTPServer.Credentials = New System.Net.NetworkCredential("NAME#gmail.com", "Password")
SMTPServer.EnableSsl = True
Try
SMTPServer.Send(MyMailMessage)
'MessageBox.Show("Email Sent")
Catch ex As SmtpException
'MessageBox.Show(ex.Message)
End Try
Dim continueUrl As String = RegisterUser.ContinueDestinationPageUrl
If String.IsNullOrEmpty(continueUrl) Then
continueUrl = "~/"
End If
Response.Redirect(continueUrl)
End Sub
End Class
Any help?
Change the port number Gmail SMTP port is : 465
Use this
SMTPServer.Port = 465
So I ended up having to use Port = 587
Thank you for the help!

Passing a NULL value to a GUID

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.

Jabber-net Send message (VB.NET)

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.

Resources