Related
Dim smtp As New SmtpClient
Dim mail As New MailMessage
smtp.Credentials = New Net.NetworkCredential("mail#gmail", "password")
mail.From = New MailAddress("mail#gmail.com")
mail.To.Add(totxt.Text$)
mail.Body = bodytxt.Text
If Not ListBox1.Items.Count <= 0 Then
Dim d As Integer
Dim attach As New Attachment(ListBox1.Items(d))
mail.Attachments.Add(attach)
End If
mail.Subject = subjecttxt.Text
smtp.EnableSsl = True
smtp.Port = "587"
smtp.Host = "smtp.gmail.com"
smtp.Send(mail)
smtp.Dispose()
done.Text = "Mail sent"
PictureBox4.BackgroundImage = My.Resources.tickfnl
dtls.Visible = False
I am trying to send email from my gmail account.But i am getting the error "The SMTP Server requires a secure connection".I even enabled LESS-SECURE APP login in my account settings.The password and email address is correct.I tried another email but same issue.Any fix ?
I TRIED ALL THE SOLUTIONS FROM THE DUPLICATE LINK,STILL THE SAME PROBLEM
**IF I REMOVE THIS LINE
smtl.enablessl=true
then i get this error
the server resposnse was 5.7.0 **
Fixed the error using EASendMail
Fixed it using EASendmail :
Panel6.Visible = True
done.Text = "Sending..."
''''''''''''''''''''''''
Dim oMail As New SmtpMail("TryIt")
Dim oSmtp As New EASendMail.SmtpClient()
oMail.From = fromtxt.Text
oMail.To = New AddressCollection(totxt.Text)
oMail.Subject = subjecttxt.Text
If html.CheckAlign = True Then
oMail.HtmlBody = bodytxt.Text
Else
oMail.TextBody = bodytxt.Text
End If
Dim oServer As New SmtpServer(MailConfig.host.Text)
oServer.Port = MailConfig.port.Text
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
oServer.User = fromtxt.Text
oServer.Password = MailConfig.password.Text
Dim r As Integer
If ListBox1.Items.Count <= 0 Then
Else
oMail.AddAttachment(ListBox1.Items(r))
End If
oSmtp.LogFileName = Application.StartupPath & "\maillog.log"
Try
oSmtp.SendMail(oServer, oMail)
done.Text = "Mail sent !"
PictureBox4.BackgroundImage = My.Resources.tickfnl
Catch ex As Exception
aa = MsgBox(ex.Message)
done.Text = "Sending failed."
PictureBox4.BackgroundImage = My.Resources.excll
End Try
I have a windows form with a DataGridView with multiple data binding sources. The form loads correctly with the appropriate data,
but when i scroll (either scrollbar or mouse wheel), it turns into this:
If i refresh the form on new line selection, it goes back to the top of the form. I see that there is a DataGridView.Scroll event. What do i need to do with it? Is there something else that i need to change to make my form look pretty again?
thx!
EDIT
Below is the code that is run to the point. There is nothing additional that handles the way the form is drawn/redrawn, and there is no event handling on DataGridView1.scroll
Imports datagridviewautofilter
Imports System.Data.SqlClient
Public Class AssignShipDateForm
'sql datastream connection variables
Dim Conn As New System.Data.SqlClient.SqlConnection 'sql server datastream connection
Dim Cmd As New System.Data.SqlClient.SqlCommand 'sql command vars
Dim SqlQuery As String 'string var used to hold various SQL queries
Dim SqlInsertQuery As String 'sql insert query for data adapter
Dim SqlUpdateQuery As String 'sql update query for data adapter
Dim SqlDeleteQuery As String 'sql delete query for data adapter
Dim data As System.Data.SqlClient.SqlDataReader 'datareader object variable
Dim ConnString As String
Dim da As SqlDataAdapter
'MasterVars table variables
Public Vers As String = Nothing 'tally sheet version
Public Testing As Boolean = False 'tf testing
Public SendMailAcct As String = Nothing 'send email account for automated emails
Public SendMailPW As String = Nothing 'password for email account
Public SMTPUseSSL As Boolean = True ' SMTP SSL
Public SMTPAuthenticate As Integer = 0 'Authenticate SMTP
Public SMTPServer As String = Nothing 'Email Server
Public SendUsing As Integer = 0 'Send Using
Public SMTPServerPort As Integer = 0 'SMTP Email Server Port
Public TestingEmail As String = Nothing 'email account that all emails should be directed to when version is testing
Public PrePricingEmail As String = Nothing 'email account that all prod prepricing emails should be directed to
Public ImperataEmail As String = Nothing 'email account that all prod Imperata emails should be directed to (for permits etc)
Public DirectShipEmail1 As String = Nothing 'email account that all prod direct ship orders should be directed to
Public DirectShipEmail2 As String = Nothing 'email account that all prod direct ship orders should be directed to
Public DirectShipEmail3 As String = Nothing 'email account that all prod direct ship orders should be directed to
Public DirectShipEmail4 As String = Nothing 'email account that all prod direct ship orders should be directed to
'user security variables
Public EMailAddress As String = Nothing 'User's email address
Public ThePersonsName As String = Nothing 'User's name
Public Logistics As String = Nothing 'logistics module access level
'close form with changes pending variables
Dim CloseForm As New Shared_Code.SharedCode
Dim ShouldICloseForm As String = Nothing 'determiniation if the form should be closed or not
'error reporting variables
Dim ErrorReporting As New ErrorReporting.ErrorReporting
Public Shared ErrCode As String = Nothing 'error code
Public Shared ErrVar As String = Nothing 'variable that caused error
Public Shared ErrorCounter As Integer = 0 'error Counter
Public Shared ErrAct As Boolean = False 't/f fatal error
'INITIALIZE FORM
Dim FirstPass As Boolean = True 't/f switch to determine if form initialize is on a first pass or subsequent pass
'CELL VALUE CHANGED
Dim RowUpdated As Boolean = False 't/f flag to set if the row has been updated
Dim SelectedShipDate As String = Nothing 'selected ship date
Dim SelectedShipDateCounter As Integer = 0 'selected ship date PKEY for TempTable
Dim NumberOfTrucksAvailable As Integer = 0 'number of trucks available for selected Ship Date
Dim DefaultPickDateCounter As Integer = 0 'counter (PKEY) for default pick date
Dim DefaultPickDate As String = Nothing 'default pick date derived from PKEY
Dim i As Integer = 0 'counter variable for adding number of trucks available from MasterBusinessDatesTable
'SAVE BUTTON
Dim vbYN As String = Nothing 'vbyn for msgbox
Dim PickID As String = Nothing 'Pkey for logistics records
Dim DTS As DateTime = Nothing 'DTS for updates
'********************************************************************************
'* *
'*CBB00: FORM LOAD *
'* *
'********************************************************************************
Public Sub New(ByRef vers As String, ByRef testing As Boolean, ByRef SendMailAcct As String, ByRef SendMailPW As String, ByVal SMTPUseSSL As Boolean, ByVal SMTPAuthenticate As Integer, ByVal SMTPServer As String, ByVal SendUsing As Integer, ByVal SMTPServerPort As Integer, ByRef TestingEmail As String, ByRef PrePricingEmail As String, ByRef ImperataEmail As String, ByRef DirectShipEmail1 As String, ByRef DirectShipEmail2 As String, ByRef DirectShipEmail3 As String, ByRef DirectShipEmail4 As String, ByRef EMailAddress As String, ByRef ThePersonsName As String, ByRef Logistics As String)
InitializeComponent()
Me.Vers = vers
Me.Testing = testing
Me.SendMailAcct = SendMailAcct
Me.SendMailPW = SendMailPW
Me.SMTPUseSSL = SMTPUseSSL
Me.SMTPAuthenticate = SMTPAuthenticate
Me.SMTPServer = SMTPServer
Me.SendUsing = SendUsing
Me.SMTPServerPort = SMTPServerPort
Me.TestingEmail = TestingEmail
Me.PrePricingEmail = PrePricingEmail
Me.ImperataEmail = ImperataEmail
Me.DirectShipEmail1 = DirectShipEmail1
Me.DirectShipEmail2 = DirectShipEmail2
Me.DirectShipEmail3 = DirectShipEmail3
Me.DirectShipEmail4 = DirectShipEmail4
Me.EMailAddress = EMailAddress
Me.ThePersonsName = ThePersonsName
Me.Logistics = Logistics
'set connection string and form for prod vs. test
If testing = True Then
ConnString = "data Source=SQL01;Initial Catalog=TallySheetTest;Integrated Security=SSPI;"
Me.Text = "Assign Ship Dates " & vers & " TESTING"
Else
ConnString = "data Source=SQL01;Initial Catalog=TallySheet;Integrated Security=SSPI;"
Me.Text = "Assign Ship Dates " & vers
End If
For Each col As DataGridViewColumn In DataGridView1.Columns
col.HeaderCell = New DataGridViewAutoFilterColumnHeaderCell(col.HeaderCell)
Next
DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True
Call FormInitialize()
End Sub
'********************************************************************************
'* *
'*CBC00: FORM INITIALIZE *
'* *
'********************************************************************************
Public Sub FormInitialize()
'clear Dataset
Me.TallySheetDataSet.Clear()
If FirstPass = True Then
'Do nothing
Else
'????????
End If
FirstPass = False
'Set buttons
Select Case Logistics
Case "I"
Button1.Enabled = False
Button2.Enabled = False
Case Else
Button1.Enabled = True
Button2.Enabled = False
End Select
'TODO: This line of code loads data into the 'TallySheetDataSet.TruckTypeTable' table. You can move, or remove it, as needed.
Me.TruckTypeTableTableAdapter.Fill(Me.TallySheetDataSet.TruckTypeTable)
'SPCBC0001 Check if TempTable1 is empty
Try
Using Conn = New SqlConnection(ConnString)
Dim cmd As New SqlCommand
cmd.Connection = Conn
cmd.CommandText = "SPCBC0001"
cmd.CommandType = CommandType.StoredProcedure
Conn.Open()
data = cmd.ExecuteReader()
data.Read()
If data.HasRows = True Then
ErrCode = "CBC00-03"
ErrVar = "TempTable1"
ErrorCounter = ErrorCounter + 1
ErrAct = ErrorReporting.YouBrokeMyProgram("", ErrCode, ErrVar, ErrorCounter, Testing, Vers, TestingEmail, SendMailAcct, SendMailPW, EMailAddress, SMTPUseSSL, SMTPAuthenticate, SMTPServer, SendUsing, SMTPServerPort)
vbYN = MsgBox("Would you like to clear temporary tables?", vbQuestion + vbYesNo + vbSystemModal, "")
If vbYN = vbYes Then
Call ClearTempTables()
Else
Exit Sub
End If
End If
End Using
Catch ex As SqlException
ErrCode = "CBC00-04"
ErrVar = "SPCBC0001;" & vbCrLf & vbCrLf & ex.Message
ErrorCounter = ErrorCounter + 1
ErrAct = ErrorReporting.YouBrokeMyProgram("", ErrCode, ErrVar, ErrorCounter, Testing, Vers, TestingEmail, SendMailAcct, SendMailPW, EMailAddress, SMTPUseSSL, SMTPAuthenticate, SMTPServer, SendUsing, SMTPServerPort)
If ErrAct = True Then
Exit Sub
End If
Finally
Conn.Close()
Conn.Dispose()
End Try
'SPCBC0002 - Check if TempTable2 is empty
Try
Using Conn = New SqlConnection(ConnString)
Dim cmd As New SqlCommand
cmd.Connection = Conn
cmd.CommandText = "SPCBC0002"
cmd.CommandType = CommandType.StoredProcedure
Conn.Open()
data = cmd.ExecuteReader()
data.Read()
If data.HasRows = True Then
ErrCode = "CBC00-06"
ErrVar = "TempTable2"
ErrorCounter = ErrorCounter + 1
ErrAct = ErrorReporting.YouBrokeMyProgram("", ErrCode, ErrVar, ErrorCounter, Testing, Vers, TestingEmail, SendMailAcct, SendMailPW, EMailAddress, SMTPUseSSL, SMTPAuthenticate, SMTPServer, SendUsing, SMTPServerPort)
vbYN = MsgBox("Would you like to clear temporary tables?", vbQuestion + vbYesNo + vbSystemModal, "")
If vbYN = vbYes Then
Call ClearTempTables()
Else
Exit Sub
End If
End If
End Using
Catch ex As SqlException
ErrCode = "CBC00-07"
ErrVar = "SPCBC0002" & vbCrLf & vbCrLf & ex.Message
ErrorCounter = ErrorCounter + 1
ErrAct = ErrorReporting.YouBrokeMyProgram("", ErrCode, ErrVar, ErrorCounter, Testing, Vers, TestingEmail, SendMailAcct, SendMailPW, EMailAddress, SMTPUseSSL, SMTPAuthenticate, SMTPServer, SendUsing, SMTPServerPort)
If ErrAct = True Then
Exit Sub
End If
Finally
Conn.Close()
Conn.Dispose()
End Try
'SPCBC0003 - Fill TempTable1 from MasterOrderTable, Customer, MasterLog
Try
Using Conn = New SqlConnection(ConnString)
Dim cmd As New SqlCommand
cmd.Connection = Conn
cmd.CommandText = "SPCBC0003"
cmd.CommandType = CommandType.StoredProcedure
Conn.Open()
cmd.ExecuteNonQuery()
End Using
Catch ex As Exception
ErrCode = "CBC00-01"
ErrVar = "SPCBC0003" & vbCrLf & vbCrLf & ex.Message
ErrorCounter = ErrorCounter + 1
ErrAct = ErrorReporting.YouBrokeMyProgram("", ErrCode, ErrVar, ErrorCounter, Testing, Vers, TestingEmail, SendMailAcct, SendMailPW, EMailAddress, SMTPUseSSL, SMTPAuthenticate, SMTPServer, SendUsing, SMTPServerPort)
If ErrAct = True Then
Exit Sub
End If
Finally
Conn.Close()
Conn.Dispose()
End Try
'SPCBC0004 - Fill DataSet TempTable1 from TempTable1
Try
Using Conn = New SqlConnection(ConnString)
Dim cmd As New SqlCommand("SPCBC0004", Conn)
cmd.CommandType = CommandType.StoredProcedure
Dim da As New SqlDataAdapter(cmd)
da.Fill(Me.TallySheetDataSet.TempTable1MasterOrders)
End Using
Catch ex As SqlException
ErrCode = "CBC00-05"
ErrVar = "SPCBC0004" & vbCrLf & vbCrLf & ex.Message
ErrorCounter = ErrorCounter + 1
ErrAct = ErrorReporting.YouBrokeMyProgram("", ErrCode, ErrVar, ErrorCounter, Testing, Vers, TestingEmail, SendMailAcct, SendMailPW, EMailAddress, SMTPUseSSL, SMTPAuthenticate, SMTPServer, SendUsing, SMTPServerPort)
If ErrAct = True Then
Exit Sub
End If
Finally
Conn.Close()
Conn.Dispose()
End Try
'handling if no rows exist
If TallySheetDataSet.TempTable1MasterOrders.Rows.Count = 0 Then
MsgBox("No open orders") '<-------------------------------- add error reporting?
Exit Sub
End If
'SPCBC0005 - Fill TempTable2 from MasterBusinessDatesTable
Try
Using Conn = New SqlConnection(ConnString)
Dim cmd As New SqlCommand
cmd.Connection = Conn
cmd.CommandText = "SPCBC0005"
cmd.CommandType = CommandType.StoredProcedure
Conn.Open()
cmd.ExecuteNonQuery()
End Using
Catch ex As SqlException
ErrCode = "CBC00-02"
ErrVar = "SPCBC0005" & vbCrLf & vbCrLf & ex.Message
ErrorCounter = ErrorCounter + 1
ErrAct = ErrorReporting.YouBrokeMyProgram("", ErrCode, ErrVar, ErrorCounter, Testing, Vers, TestingEmail, SendMailAcct, SendMailPW, EMailAddress, SMTPUseSSL, SMTPAuthenticate, SMTPServer, SendUsing, SMTPServerPort)
If ErrAct = True Then
Exit Sub
End If
Finally
Conn.Close()
Conn.Dispose()
End Try
'SPCBC0006 - Fill DataSet TempTable2 from TempTable2
Try
Using Conn = New SqlConnection(ConnString)
Dim cmd As New SqlCommand("SPCBC0006", Conn)
cmd.CommandType = CommandType.StoredProcedure
Dim da As New SqlDataAdapter(cmd)
da.Fill(Me.TallySheetDataSet.TempTable2BusinessDates)
End Using
Catch ex As SqlException
ErrCode = "CBC00-08"
ErrVar = "SPCBC0006" & vbCrLf & vbCrLf & ex.Message
ErrorCounter = ErrorCounter + 1
ErrAct = ErrorReporting.YouBrokeMyProgram("", ErrCode, ErrVar, ErrorCounter, Testing, Vers, TestingEmail, SendMailAcct, SendMailPW, EMailAddress, SMTPUseSSL, SMTPAuthenticate, SMTPServer, SendUsing, SMTPServerPort)
If ErrAct = True Then
Exit Sub
End If
Finally
Conn.Close()
Conn.Dispose()
End Try
'set ALL columns read only property to true
DataGridView1.Columns(0).ReadOnly = True
DataGridView1.Columns(1).ReadOnly = True
DataGridView1.Columns(2).ReadOnly = True
DataGridView1.Columns(3).ReadOnly = True
DataGridView1.Columns(4).ReadOnly = True
DataGridView1.Columns(5).ReadOnly = True
DataGridView1.Columns(6).ReadOnly = True
DataGridView1.Columns(7).ReadOnly = True
DataGridView1.Columns(8).ReadOnly = True
DataGridView1.Columns(9).ReadOnly = True
DataGridView1.Columns(10).ReadOnly = True
DataGridView1.Columns(11).ReadOnly = True
DataGridView1.Columns(12).ReadOnly = True
DataGridView1.Columns(13).ReadOnly = True
DataGridView1.Columns(14).ReadOnly = True
DataGridView1.Columns(15).ReadOnly = True
DataGridView1.Columns(16).ReadOnly = True
DataGridView1.Columns(17).ReadOnly = True
DataGridView1.Columns(18).ReadOnly = True
DataGridView1.Columns(19).ReadOnly = True
DataGridView1.Columns(20).ReadOnly = True
DataGridView1.Columns(21).ReadOnly = True
DataGridView1.Columns(22).ReadOnly = True
DataGridView1.Columns(23).ReadOnly = True
'Refresh form
Me.Refresh()
DataGridView1.Refresh()
End Sub
EDIT
i have an empty handler for DataGridView1.DataError. I added a message box and the "Ship Date" throws an error for every value in the column, then when you scroll, it throws an error for every new "Ship Date" cell that appears. The error is for a null value being displayed in a column that doesn't accept a null value. The null value is an attempt to suppress the value '1900-01-01' from being displayed.
the display errors are caused by an error message being suppressed due to a null value being displayed in a column that doesn't accept a null value. The null value is an attempt to suppress the value '1900-01-01' from being displayed.
I am trying to make a ConsoleApplication attach all files in a folder to an email and send it. I know how to do it with a single attachment, but for the life of me, I cannot figure out how to attach all items in a folder.
Current code:
Sub Main()
Try
Dim mail As New MailMessage("from", "to")
Dim client As New SmtpClient()
client.Port = 25
client.DeliveryMethod = SmtpDeliveryMethod.Network
client.UseDefaultCredentials = False
client.Host = ""
mail.Subject = "" + DateTime.Now.AddDays(-1).ToShortDateString()
mail.IsBodyHtml = True
mail.Body = "Test"
Dim file As System.Net.Mail.Attachment
file = New System.Net.Mail.Attachment("Path to single file")
mail.Attachments.Add(file)
client.Send(mail)
Return
Catch [error] As Exception
MsgBox("error")
Return
End Try
End Sub
Thanks in advance
EDIT:
I tried the below code that I found on another post, but it just errors out (and using the ConsoleApplication, I am not sure how to view the exact error its giving)
For Each filePath As String In Directory.GetFiles(My.Settings.FileLoc1)
Dim Attach As New Net.Mail.Attachment(filePath)
mail.Attachments.Add(Attach)
Next
I got it working!
Sub Main()
Try
Dim mail As New MailMessage("from", "too")
Dim client As New SmtpClient()
client.Port = 25
client.DeliveryMethod = SmtpDeliveryMethod.Network
client.UseDefaultCredentials = False
client.Host = ""
mail.Subject = "" + DateTime.Now.AddDays(-1).ToShortDateString()
mail.IsBodyHtml = True
mail.Body = "Test"
For Each filePath As String In Directory.GetFiles(My.Settings.FileLoc1)
Dim Attach As New Net.Mail.Attachment(filePath)
mail.Attachments.Add(Attach)
Next
client.Send(mail)
Return
Catch [error] As Exception
MsgBox("error")
Return
End Try
End Sub
My program has been using:
Dim DLLink1 As String
DLLink1 = Trim(TextBox2.Text)
Dim DownloadDirectory1 As String
DownloadDirectory1 = Trim(TextBox4.Text)
Try
Button3.Enabled = False
' My.Computer.Network.DownloadFile(DLLink1, (DownloadDirectory1 + "/UpdatedClient.zip"))
Dim HttpReq As HttpWebRequest = DirectCast(WebRequest.Create(DLLink1), HttpWebRequest)
Using HttpResponse As HttpWebResponse = DirectCast(HttpReq.GetResponse(), HttpWebResponse)
Using Reader As New BinaryReader(HttpResponse.GetResponseStream())
Dim RdByte As Byte() = Reader.ReadBytes(1 * 1024 * 1024 * 10)
Using FStream As New FileStream(DownloadDirectory1 + "/UpdatedClient.zip", FileMode.Create)
FStream.Write(RdByte, 0, RdByte.Length)
End Using
End Using
End Using
Finally
MsgBox("Finished Download.")
Button3.Enabled = True
Label4.Visible = True
I tried this previously, and it didn't work at all:
My.Computer.Network.DownloadFile(DLLink1, (DownloadDirectory1 + "/UpdatedClient.zip"))
The website requires you to be logged in, so I made a spare account for the program:
WebBrowser1.Navigate("http://www.mpgh.net/forum/admincp/")
Timer1.Start()
Button2.Enabled = False
Then
WebBrowser1.Document.GetElementById("vb_login_username").SetAttribute("value", "AutoUpdaterAccount")
WebBrowser1.Document.GetElementById("vb_login_password").SetAttribute("value", "password")
Dim allelements As HtmlElementCollection = WebBrowser1.Document.All
For Each webpageelement As HtmlElement In allelements
If webpageelement.GetAttribute("type") = "submit" Then
webpageelement.InvokeMember("click")
Timer1.Stop()
Label5.Text = "Authorized."
Button2.Enabled = True
So now you're logged into the account, on the website, but when the code above to download runs, it downloads a zip, but it's corrupted. So I opened it with notepad++ and this is what I get (Does this mean it didn't login for the download, and it only logged in with the webbrowser and they aren't linked? Or something? Like My firefox logins aren't linked with chrome?:
The code is huge, it's like a HTML coding. Here is the link to a online notepad I put it on:
http://shrib.com/nCOucdfL
Another thing, a webbrowser can't be showing on the program, it can be on the outside not showing, like I did with the login. They also can't click the save button like on a normal web browser when a window pops up, I want it to download automatically to where they set it using a button which sets the directory as DownloadDirectory1
It must be your lucky day because today I woke up and decided that I would like to help you with your cause. I first tried to get the download to work with the web browser control but unfortunately I am sure this is not possible without extending the web browser control and we don't want to do that today.
As I mentioned in the comments, the only way I really know that this is possible (without user interaction) is to log in via the HttpWebRequest method. It's pretty tricky stuff. Definitely not for beginners.
Now I must admit that this isn't the cleanest, most "proper" and user-friendly code around, so if anyone wants to suggest a better way to do things, I am all ears.
I suggest you test this first before you incorporate it into your existing app. Just create a new vb.net app and replace all of the code in Form1 with the code below. You will have to update the usernamehere and passwordhere strings with your real username and password. Also, the file is saving to C:\file.rar by default so you can change this path if you want. This code completely removes the need for the web browser control (unless you are using it for something else) so most likely you can remove that from your real application once you incorporate this properly:
Imports System.Net
Imports System.IO
Imports System.Text
Public Class Form1
Private Const gsUserAgent As String = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0"
Const sUsername As String = "usernamehere"
Const sPassword As String = "passwordhere"
Const sMainURL As String = "http://www.mpgh.net/"
Const sCheckLoginURL As String = "http://www.mpgh.net/forum/login.php?do=login"
Const sDownloadURL As String = "http://www.mpgh.net/forum/attachment.php?attachmentid=266579&d=1417312178"
Const sCookieLoggedInMessage As String = "mpgh_imloggedin=yes"
Dim oCookieCollection As CookieCollection = Nothing
Dim sSaveFile As String = "c:\file.rar"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
StartScrape()
End Sub
Private Sub StartScrape()
Try
Dim bContinue As Boolean = True
Dim sPostData(15) As String
sPostData(0) = UrlEncode("vb_login_username")
sPostData(1) = UrlEncode(sUsername)
sPostData(2) = UrlEncode("vb_login_password")
sPostData(3) = UrlEncode(sPassword)
sPostData(4) = UrlEncode("vb_login_password_hint")
sPostData(5) = UrlEncode("Password")
sPostData(6) = UrlEncode("s")
sPostData(7) = UrlEncode("")
sPostData(8) = UrlEncode("securitytoken")
sPostData(9) = UrlEncode("guest")
sPostData(10) = UrlEncode("do")
sPostData(11) = UrlEncode("login")
sPostData(12) = UrlEncode("vb_login_md5password")
sPostData(13) = UrlEncode("")
sPostData(14) = UrlEncode("vb_login_md5password_utf")
sPostData(15) = UrlEncode("")
If GetMethod(sMainURL) = True Then
If SetMethod(sCheckLoginURL, sPostData, sMainURL) = True Then
' Login successful
If DownloadMethod(sDownloadURL, sMainURL) = True Then
MessageBox.Show("File downloaded successfully")
Else
MessageBox.Show("Error downloading file")
End If
End If
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Function GetMethod(ByVal sPage As String) As Boolean
Dim req As HttpWebRequest
Dim resp As HttpWebResponse
Dim stw As StreamReader
Dim bReturn As Boolean = True
Try
req = HttpWebRequest.Create(sPage)
req.Method = "GET"
req.AllowAutoRedirect = False
req.UserAgent = gsUserAgent
req.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"
req.Headers.Add("Accept-Language", "en-us,en;q=0.5")
req.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7")
req.Headers.Add("Keep-Alive", "300")
req.KeepAlive = True
resp = req.GetResponse ' Get the response from the server
If req.HaveResponse Then
' Save the cookie info if applicable
SaveCookies(resp.Headers("Set-Cookie"))
resp = req.GetResponse ' Get the response from the server
stw = New StreamReader(resp.GetResponseStream)
stw.ReadToEnd() ' Read the response from the server, but we do not save it
Else
MessageBox.Show("No response received from host " & sPage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
bReturn = False
End If
Catch exc As WebException
MessageBox.Show("Network Error: " & exc.Message.ToString & " Status Code: " & exc.Status.ToString & " from " & sPage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
bReturn = False
End Try
Return bReturn
End Function
Private Function SetMethod(ByVal sPage As String, ByVal sPostData() As String, sReferer As String) As Boolean
Dim bReturn As Boolean = False
Dim req As HttpWebRequest
Dim resp As HttpWebResponse
Dim str As StreamWriter
Dim sPostDataValue As String = ""
Try
req = HttpWebRequest.Create(sPage)
req.Method = "POST"
req.UserAgent = gsUserAgent
req.Accept = "application/x-shockwave-flash,text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"
req.Headers.Add("Accept-Language", "en-us,en;q=0.5")
req.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7")
req.Referer = sReferer
req.ContentType = "application/x-www-form-urlencoded"
req.Headers.Add("Pragma", "no-cache")
req.Headers.Add("Keep-Alive", "300")
If oCookieCollection IsNot Nothing Then
' Pass cookie info from the login page
req.CookieContainer = SetCookieContainer(sPage)
End If
str = New StreamWriter(req.GetRequestStream)
If sPostData.Count Mod 2 = 0 Then
' There is an even number of post names and values
For i As Int32 = 0 To sPostData.Count - 1 Step 2
' Put the post data together into one string
sPostDataValue &= sPostData(i) & "=" & sPostData(i + 1) & "&"
Next i
sPostDataValue = sPostDataValue.Substring(0, sPostDataValue.Length - 1) ' This will remove the extra "&" at the end that was added from the for loop above
' Post the data to the server
str.Write(sPostDataValue)
str.Close()
' Get the response
resp = req.GetResponse
If req.HaveResponse Then
If resp.Headers("Set-Cookie").IndexOf(sCookieLoggedInMessage) > -1 Then
' Save the cookie info
SaveCookies(resp.Headers("Set-Cookie"))
bReturn = True
Else
MessageBox.Show("The email or password you entered are incorrect." & vbCrLf & vbCrLf & "Please try again.", "Unable to log in", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
bReturn = False
End If
Else
' This should probably never happen.. but if it does, we give a message
MessageBox.Show("The email or password you entered are incorrect." & vbCrLf & vbCrLf & "Please try again.", "Unable to log in", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
bReturn = False
End If
Else
' Did not specify the correct amount of parameters so we cannot continue
MessageBox.Show("POST error. Did not supply the correct amount of post data for " & sPage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
bReturn = False
End If
Catch ex As Exception
MessageBox.Show("POST error. " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
bReturn = False
End Try
Return bReturn
End Function
Private Function DownloadMethod(ByVal sPage As String, sReferer As String) As Boolean
Dim req As HttpWebRequest
Dim bReturn As Boolean = False
Try
req = HttpWebRequest.Create(sPage)
req.Method = "GET"
req.AllowAutoRedirect = False
req.UserAgent = gsUserAgent
req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
req.Headers.Add("Accept-Language", "en-US,en;q=0.5")
req.Headers.Add("Accept-Encoding", "gzip, deflate")
req.Headers.Add("Keep-Alive", "300")
req.KeepAlive = True
If oCookieCollection IsNot Nothing Then
' Set cookie info so that we continue to be logged in
req.CookieContainer = SetCookieContainer(sPage)
End If
' Save file to disk
Using oResponse As System.Net.WebResponse = CType(req.GetResponse, System.Net.WebResponse)
Using responseStream As IO.Stream = oResponse.GetResponseStream
Using fs As New IO.FileStream(sSaveFile, FileMode.Create, FileAccess.Write)
Dim buffer(2047) As Byte
Dim read As Integer
Do
read = responseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
Loop Until read = 0
responseStream.Close()
fs.Flush()
fs.Close()
End Using
responseStream.Close()
End Using
oResponse.Close()
End Using
bReturn = True
Catch exc As WebException
MessageBox.Show("Network Error: " & exc.Message.ToString & " Status Code: " & exc.Status.ToString & " from " & sPage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
bReturn = False
End Try
Return bReturn
End Function
Private Function SetCookieContainer(sPage As String) As System.Net.CookieContainer
Dim oCookieContainerObject As New System.Net.CookieContainer
Dim oCookie As System.Net.Cookie
For c As Int32 = 0 To oCookieCollection.Count - 1
If IsDate(oCookieCollection(c).Value) = True Then
' Fix dates as they seem to cause errors/problems
oCookieCollection(c).Value = Format(CDate(oCookieCollection(c).Value), "dd-MMM-yyyy hh:mm:ss")
End If
oCookie = New System.Net.Cookie
oCookie.Name = oCookieCollection(c).Name
oCookie.Value = oCookieCollection(c).Value
oCookie.Domain = New Uri(sPage).Host
oCookie.Secure = False
oCookieContainerObject.Add(oCookie)
Next
Return oCookieContainerObject
End Function
Private Sub SaveCookies(sCookieString As String)
Dim sCookieStrings() As String = sCookieString.Trim.Replace(" HttpOnly,", "").Replace(" HttpOnly", "").Replace(" domain=.mpgh.net,", "").Split(";".ToCharArray())
oCookieCollection = New CookieCollection
For Each sCookie As String In sCookieStrings
If sCookie.Trim <> "" Then
Dim sName As String = sCookie.Trim().Split("=".ToCharArray())(0)
Dim sValue As String = sCookie.Trim().Split("=".ToCharArray())(1)
oCookieCollection.Add(New Cookie(sName, sValue))
End If
Next
End Sub
Private Function UrlEncode(ByRef URLText As String) As String
Dim AscCode As Integer
Dim EncText As String = ""
Dim bStr() As Byte = Encoding.ASCII.GetBytes(URLText)
Try
For i As Long = 0 To UBound(bStr)
AscCode = bStr(i)
Select Case AscCode
Case 48 To 57, 65 To 90, 97 To 122, 46, 95
EncText = EncText & Chr(AscCode)
Case 32
EncText = EncText & "+"
Case Else
If AscCode < 16 Then
EncText = EncText & "%0" & Hex(AscCode)
Else
EncText = EncText & "%" & Hex(AscCode)
End If
End Select
Next i
Erase bStr
Catch ex As WebException
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Return EncText
End Function
End Class
I connected recently to SMS provider API using vb.net
I have created a group table and inserted all numbers in this group and then reach each row and send trigger the API to process sending.
The sms is not reached to all group members, its only delivered successfully to the first mobile number in the group.
How to solve this problem ? I think I have to set a delay between each sending and i did with no use. my code is below :
Function GetGroupsMobileNumbers() As ArrayList
Dim MobileNumbersArrayList As New ArrayList
For Each Contact As FilsPayComponent.ContactAddress In FilsPayComponent.ContactAddress.GetAllContactAddressByGroupId(ddlGroup.SelectedValue)
MobileNumbersArrayList.Add(Contact.Mobile)
Next
Return MobileNumbersArrayList
End Function
Protected Sub btnSend_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSend.Click
If ddlGroup.SelectedValue = 0 Then
lbResult.Text = "No groups selected"
Exit Sub
End If
Dim MobileNumbersArrayList As ArrayList
MobileNumbersArrayList = GetGroupsMobileNumbers()
If MobileNumbersArrayList.Count = 0 Then
lbResult.Text = "Group doesnt contain numbers"
Exit Sub
End If
Dim TotalNo As Integer = FilsPayComponent.ContactAddress.AddressContactsCount(ddlGroup.SelectedValue)
If MobileNumbersArrayList.Count * messagecount.Value <= FilsPayComponent.SmSUser.GetSmSUserByUserId(Context.User.Identity.Name).Balance Then
Dim txtMsg As String
Dim smstype As Integer
If hidUnicode.Value <> "1" Then
txtMsg = txtMessage.Text
smstype = 1
Else
txtMsg = ConvertTextToUnicode(txtMessage.Text)
smstype = 2
End If
Dim x As Integer
'For Each Contact As FilsPayComponent.ContactAddress In FilsPayComponent.ContactAddress.GetAllContactAddressByGroupId(ddlGroup.SelectedValue)
For Each Contact In MobileNumbersArrayList.ToArray
Dim toMobile As String = Contact.Mobile
If toMobile.Length > 10 Then
Dim ExecArrayList As ArrayList
ExecArrayList = SendSMS(toMobile, txtMsg, smstype)
'-- give the excution more time
If ExecArrayList.Count < 1 Then
Threading.Thread.Sleep(1000)
End If
'-- give the excution more time
If ExecArrayList.Count < 1 Then
Threading.Thread.Sleep(1000)
End If
'-- give the excution more time
If ExecArrayList.Count < 1 Then
Threading.Thread.Sleep(1000)
End If
x = x + 1
' lbresult.Text = "Sent Successfully"
End If
Next
FilsPayComponent.SmSUser.RemoveSmsCredit(Context.User.Identity.Name, messagecount.Value * x)
Dim NewsmsarchiveItem As New FilsPayComponent.smsarchive
NewsmsarchiveItem.FromMobile = txtSenderID.Text
NewsmsarchiveItem.ToMobile = "0"
NewsmsarchiveItem.GroupId = ddlGroup.SelectedValue
NewsmsarchiveItem.DateSent = DateTime.Now
NewsmsarchiveItem.Msg = txtMessage.Text
NewsmsarchiveItem.GroupCount = x
NewsmsarchiveItem.Optional1 = Context.User.Identity.Name
NewsmsarchiveItem.Optional2 = "1"
NewsmsarchiveItem.MessageNo = messagecount.Value
Try
NewsmsarchiveItem.Addsmsarchive()
lbResult.Text = "Message sent successfully"
btnSend.Visible = False
Catch ex As Exception
lbResult.Text = ex.Message
End Try
Else
lbResult.Text = "Not enough credit, please refill "
End If
End Sub
Sub SendSMS(ByVal toMobile As String, ByVal txtMsg As String, ByVal smstype As Integer)
Dim hwReq As HttpWebRequest
Dim hwRes As HttpWebResponse
Dim smsUser As String = "xxxxxx"
Dim smsPassword As String = "xxxxxx"
Dim smsSender As String = "xxxxxx"
Dim strPostData As String = String.Format("username={0}&password={1}&destination={2}&message={3}&type={4}&dlr=1&source={5}", Server.UrlEncode(smsUser), Server.UrlEncode(smsPassword), Server.UrlEncode(toMobile), Server.UrlEncode(txtMsg), Server.UrlEncode(smstype), Server.UrlEncode(smsSender))
Dim strResult As String = ""
Try
hwReq = DirectCast(WebRequest.Create("http://xxxxx:8080/bulksms/bulksms?"), HttpWebRequest)
hwReq.Method = "POST"
hwReq.ContentType = "application/x-www-form-urlencoded"
hwReq.ContentLength = strPostData.Length
Dim arrByteData As Byte() = ASCIIEncoding.ASCII.GetBytes(strPostData)
hwReq.GetRequestStream().Write(arrByteData, 0, arrByteData.Length)
hwRes = DirectCast(hwReq.GetResponse(), HttpWebResponse)
If hwRes.StatusCode = HttpStatusCode.OK Then
Dim srdrResponse As New StreamReader(hwRes.GetResponseStream(), Encoding.UTF8)
Dim strResponse As String = srdrResponse.ReadToEnd().Trim()
Select Case strResponse
Case "01"
strResult = "success"
Exit Select
Case Else
strResult = "Error: " + strResponse
Exit Select
End Select
End If
Catch wex As WebException
strResult = "Error, " + wex.Message
Catch ex As Exception
strResult = "Error, " + ex.Message
Finally
hwReq = Nothing
hwRes = Nothing
End Try
End Sub
If function GetGroupsMobileNumbers() does not return an array list of numbers (as Strings)
then comment out. MobileNumbersArrayList = GetGroupsMobileNumbers()
then use the commented out code below (with three of your own tel. numbers) to set it for testing.
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
If ddlGroup.SelectedValue = 0 Then
lbResult.Text = "No groups selected"
Exit Sub
End If
Dim MobileNumbersArrayList As New ArrayList
MobileNumbersArrayList = GetGroupsMobileNumbers()
'MobileNumbersArrayList.Add("07702123456")
'MobileNumbersArrayList.Add("07702123457")
'MobileNumbersArrayList.Add("07702123458")
If MobileNumbersArrayList.Count = 0 Then
lbResult.Text = "Group doesnt contain numbers"
Exit Sub
End If
Dim TotalNo As Integer = FilsPayComponent.ContactAddress.AddressContactsCount(ddlGroup.SelectedValue)
If MobileNumbersArrayList.Count * messagecount.Value <= FilsPayComponent.SmSUser.GetSmSUserByUserId(Context.User.Identity.Name).Balance Then
Dim txtMsg As String
Dim smstype As Integer
If hidUnicode.Value <> "1" Then
txtMsg = txtMessage.Text
smstype = 1
Else
txtMsg = ConvertTextToUnicode(txtMessage.Text)
smstype = 2
End If
Dim x As Integer
For Each Contact In MobileNumbersArrayList
If Contact.Length > 10 Then
SendSMS(Contact, txtMsg, smstype)
x = x + 1
End If
Next
FilsPayComponent.SmSUser.RemoveSmsCredit(Context.User.Identity.Name, messagecount.Value * x)
Dim NewsmsarchiveItem As New FilsPayComponent.smsarchive
NewsmsarchiveItem.FromMobile = txtSenderID.Text
NewsmsarchiveItem.ToMobile = "0"
NewsmsarchiveItem.GroupId = ddlGroup.SelectedValue
NewsmsarchiveItem.DateSent = DateTime.Now
NewsmsarchiveItem.Msg = txtMessage.Text
NewsmsarchiveItem.GroupCount = x
NewsmsarchiveItem.Optional1 = Context.User.Identity.Name
NewsmsarchiveItem.Optional2 = "1"
NewsmsarchiveItem.MessageNo = messagecount.Value
Try
NewsmsarchiveItem.Addsmsarchive()
lbResult.Text = "Message sent successfully"
btnSend.Visible = False
Catch ex As Exception
lbResult.Text = ex.Message
End Try
Else
lbResult.Text = "Not enough credit, please refill "
End If
End Sub
This btnSend sub should work if the rest of your code is okay. Note your line.
Dim TotalNo As Integer = FilsPayComponent.ContactAddress.AddressContactsCount(ddlGroup.SelectedValue)
Doesn't appear to do anything.
If you need to set a delay you would be better off turning SendSMS into a function that returns a sent confirmation to your btnSend loop. Most texting APIs can handle lists of numbers rather than waiting for a response for each text message. Afterall they only get added to a queue at their end.