I have created a service that is supposed to pass data from SQL to CSV, by creating a CSV file. It has no errors, but i run it and nothing happens.
1) Is there something I am missing?
2) If it works, and i want to convert to txt file, is it enough to change the "CSV" to "txt" parts?
My code:
#Region "Export SQL TO CSV"
Public Shared Function WriteCSV(ByVal input As String) As String
Try
If (input Is Nothing) Then
Return String.Empty
End If
Dim containsQuote As Boolean = False
Dim containsComma As Boolean = False
Dim len As Integer = input.Length
Dim i As Integer = 0
Do While ((i < len) _
AndAlso ((containsComma = False) _
OrElse (containsQuote = False)))
Dim ch As Char = input(i)
If (ch = Microsoft.VisualBasic.ChrW(34)) Then
containsQuote = True
ElseIf (ch = Microsoft.VisualBasic.ChrW(44)) Then
containsComma = True
End If
i = (i + 1)
Loop
If (containsQuote AndAlso containsComma) Then
input = input.Replace("""", """""")
End If
If (containsComma) Then
Return """" & input & """"
Else
Return input
End If
Catch ex As Exception
Throw
End Try
End Function
Private Sub ExtoCsv(ByVal sender As Object, ByVal e As EventArgs)
Dim sb As StringBuilder = New StringBuilder
Using db As Database.RecordSet = admin.Database.OpenRecordsetReadOnly("select USERID, NAME1 from usertable WHERE I_ID=2")
Dim userid As String = db("USERID").Value
Dim name1 As String = db("NAME1").Value
For i As Integer = 1 To db.RecordCount
sb.Append(WriteCSV(userid + "," + name1 + ","))
sb.AppendLine()
db.MoveNext()
Next
End Using
File.WriteAllText("C:\Users\user1\Desktop\ex1.csv", sb.ToString)
If (Not System.IO.Directory.Exists("C:\Users\user1\Desktop\ex1")) Then
System.IO.Directory.CreateDirectory("C:\Users\user1\Desktop\ex1")
End If
End Sub
#End Region
I have been trying to create a program that will find the word the user has clicked on, in a multiline textbox. This procedure is based on the index from the position of the click. The code I implemented:
Public Class Form1
Private Sub TextBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles TextBox1.MouseDown
If e.Clicks = 1 And e.Button = MouseButtons.Left Then
'Try
Dim indexClicked As Integer = TextBox1.GetCharIndexFromPosition(New Point(e.X, e.Y))
Dim ch As Char = TextBox1.Text.Chars(indexClicked)
Dim indexOfWord As Int32
If Not ch = " " Then
Dim wordFound As Boolean
Dim previousCh As Char
Dim previousIndex As Integer = indexClicked
While Not wordFound
previousIndex = previousIndex - 1
previousCh = TextBox1.Text.Chars(previousIndex)
If previousCh = " " Then
indexOfWord = previousIndex + 1
wordFound = True
End If
End While
Else
indexOfWord = indexClicked + 1
End If
Label1.Text = indexClicked & ", " & indexOfWord
Label2.Text = GetWordByIndex(TextBox1.Text, indexOfWord)
' Catch ex As Exception
' Label2.Text = ex.Message
' End Try
End If
End Sub
Public Shared Function GetWordByIndex(input As String, index As Integer) As String
Try
Dim words = input.Split(" ")
If (index < 0) OrElse (index > words.Length - 1) Then
Throw New IndexOutOfRangeException("Index out of range!")
End If
Return words(index)
Catch ex As Exception
'handle the exception your way
Return String.Empty
End Try
End Function
End Class
The problem is that whenever the program reaches the line:
previousCh = TextBox1.Text.Chars(previousIndex)
it exits with :
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in WindowsApplication1.exe
Additional information: Index was outside the bounds of the array.
While the exception is thrown, by hovering over the previousIndex variable visual studio shows me its value: -1.
I think that previousCh = " " condition never gets true, so the program never exits the while loop, which keeps looking for the previous character. At some point int previousIndex gets negative and the program crashes. Why does not the condtion work properly?
What is the problem?
Thank you.
If you do not want to have the user double click like David Wilson suggested (which i would also agree with) then this will get the result you want. It takes into account if the previous character is a line feed or the start of the text, or the next character is a line feed or end of the text as well. You can add to the If to find "," or "." if needed.
Private Sub TextBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles TextBox1.MouseDown
If e.Clicks = 1 And e.Button = MouseButtons.Left Then
Dim startIndex As Integer = TextBox1.SelectionStart
Dim wordStartFound, wordEndFound As Boolean
Dim nextIndex, indexOfStartOfWord, indexOfEndOfWord, lengthOfWord As Integer
If Not startIndex = 0 Then
While Not wordStartFound
startIndex = startIndex - 1
If TextBox1.Text.Chars(startIndex) = " " Then
indexOfStartOfWord = startIndex + 1
wordStartFound = True
ElseIf startIndex = 0 Then
indexOfStartOfWord = startIndex
wordStartFound = True
ElseIf TextBox1.Text.Chars(startIndex) = Chr(10) Then 'Line Feed'
indexOfStartOfWord = startIndex + 1
wordStartFound = True
End If
End While
Else
indexOfStartOfWord = startIndex
End If
nextIndex = startIndex
While Not wordEndFound
nextIndex = nextIndex + 1
If TextBox1.Text.Chars(nextIndex) = " " Then
indexOfEndOfWord = nextIndex
wordEndFound = True
ElseIf nextIndex = TextBox1.TextLength - 1 Then
indexOfEndOfWord = TextBox1.TextLength
wordEndFound = True
ElseIf TextBox1.Text.Chars(nextIndex) = Chr(10) Then 'Line Feed'
indexOfEndOfWord = nextIndex
wordEndFound = True
End If
End While
lengthOfWord = indexOfEndOfWord - indexOfStartOfWord
Label2.Text = TextBox1.Text.Substring(indexOfStartOfWord, lengthOfWord)
End If
End Sub
Also in your function GetWordByIndex you split the input string into an array
Dim words = input.Split(" ")
then you say
If (index < 0) OrElse (index > words.Length - 1) Then
Throw New IndexOutOfRangeException("Index out of range!")
End If
but when you call .length on an array it returns the number of strings (or whatever is in the array) For example if the input was "The big brown fox jumped over the lazy dog", words.length - 1 will return 8. So if your index you pass through is the start of the word "over" it would fall into the Throw New IndexOutOfRangeException("Index out of range!") as the index would be 26 which is obviously greater than 8.
The code i have provided doesn't use the function to find the word but i thought i would mention that anyway.
Given a string, how do you generate all partitions of it (shown as smaller strings separated by commas)?
Also, what is the total number of partitions for a string of length n?
The following will give the result, but is not good on long strings.
String: CODE
C,O,D,E
C,O,DE
C,OD,E
C,ODE
CO,D,E
CO,DE
COD,E
String: PEACE
P,E,A,C,E
P,E,A,CE
P,E,AC,E
P,E,ACE
P,EA,C,E
P,EA,CE
P,EAC,E
PE,A,C,E
PE,A,CE
PE,AC,E
PE,ACE
PEA,C,E
PEA,CE
Sub getAllComb()
oriStr = TextBox1.Text
Dim tmp = ""
Dim k = 0
For i = 0 To oriStr.Length
For j = 1 To 3
'tmp = Mid(oriStr, i, j)
Try
tmp1(k) = oriStr.Substring(i, j)
k = k + 1
'tmp = oriStr.Substring(i, j)
'Debug.Print(tmp)
Catch ex As Exception
'Debug.Print("Error>>>>" + ex.Message)
Exit For
End Try
Next
Next
tmp = ""
For i = 0 To k
Debug.Print(i.ToString + "<i " + tmp1(i))
tmp = tmp & tmp1(i) & vbCrLf
Next
'MessageBox.Show(tmp)
Dim tmpAll1 = ""
tmpAll1 = addFunclen4(k)
MessageBox.Show(tmpAll1)
Debug.Print(tmpAll1)
TextBox1.Text = oriStr & vbCrLf & vbCrLf & tmpAll1
End Sub
Function addFunclen4(k As Integer) As String
Dim retVal = ""
Dim tmp = ""
Dim tmpAll = ""
Dim tmpStr = ""
Dim tmpAll1 = ""
For i = 0 To k
For i1 = 0 To k
For i2 = 0 To k
For i3 = 0 To k
For i4 = 0 To k
tmp = Form1.tmp1(i) + Form1.tmp1(i1) + Form1.tmp1(i2) + Form1.tmp1(i3) + Form1.tmp1(i4)
If Form1.tmp1(i) <> "" Then
If tmp = Form1.oriStr Then
tmpStr = Form1.tmp1(i) + "," + Form1.tmp1(i1) + "," + Form1.tmp1(i2) + "," + Form1.tmp1(i3) + "," + Form1.tmp1(i4)
Do While tmpStr.Contains(",,") = True
tmpStr = Replace(tmpStr, ",,", ",")
Loop
If Mid(tmpStr, tmpStr.Length, 1) = "," Then
tmpStr = Mid(tmpStr, 1, tmpStr.Length - 1)
End If
If tmpAll1.Contains(tmpStr) = False Then
tmpAll1 = tmpAll1 + tmpStr + vbCrLf
End If
End If
End If
Next
Next
Next
Next
Next
retVal = tmpAll1
Return retVal
End Function
I reckon [2^(n-1) - 1] in total:
(n-1) positions to put a comma, 2 "states" (comma or not comma), -1 for the trivial case with no commas.
A simpler algorithm would be to iterate through the number of cases and use the binary representation to determine whether to put a comma in each position.
For example (simple form with TextBox, Button and ListBox):
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.Items.Clear()
Dim s As String = TextBox1.Text
If s.Length < 2 Then
MessageBox.Show("Enter a longer string")
Return
End If
For i = 1 To Math.Pow(2, s.Length - 1) - 1
Dim result As String = s(0)
For j = 1 To s.Length - 1
result = result & CommaOrNot(i, j) & s(j)
Next
ListBox1.Items.Add(result)
Next
End Sub
Private Function CommaOrNot(i As Integer, j As Integer) As String
If (i And Math.Pow(2, j - 1)) = Math.Pow(2, j - 1) Then
Return ","
Else
Return ""
End If
End Function
I really liked Fruitbat's approach. Here's an alternate version using a slightly different mechanism for the representation of the binary number and how to determine if the comma should be included or not:
Public Class Form1
Private combinations As List(Of String)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim s As String = TextBox1.Text
If s.Length < 2 Then
MessageBox.Show("Enter a longer string")
Exit Sub
End If
Button1.Enabled = False
ListBox1.DataSource = Nothing
ListBox1.Items.Clear()
ListBox1.Items.Add("Generating combinations...")
BackgroundWorker1.RunWorkerAsync(s)
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim s As String = e.Argument
Dim combinations As New List(Of String)
Dim binary() As Char
Dim values() As Char = s.ToCharArray
Dim max As Integer = Convert.ToInt32(New String("1", s.Length - 1), 2)
Dim sb As New System.Text.StringBuilder
For i As Integer = 0 To max
sb.Clear()
binary = Convert.ToString(i, 2).PadLeft(values.Length, "0").ToCharArray
For j As Integer = 0 To values.Length - 1
sb.Append(If(binary(j) = "0", "", ","))
sb.Append(values(j))
Next
combinations.Add(sb.ToString)
Next
e.Result = combinations
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
combinations = e.Result
ListBox1.Items.Clear()
ListBox1.Items.Add("Generating combinations...Done!")
ListBox1.Items.Add("Adding Results...one moment please!")
Application.DoEvents()
ListBox1.DataSource = Nothing
ListBox1.DataSource = combinations
Button1.Enabled = True
MessageBox.Show("Done!")
End Sub
End Class
What I am trying to do is : FIRST: Check if Cell Value Exist if TRUE continue.
SECOND : If False MsgBox Invalid Ticket.
Private Sub changefound()
Dim findtxt As String = txt_Find.Text
Try
If DataGridView2.Rows.Count > 0 Then
For i As Integer = 0 To DataGridView2.Rows.Count - 1
Dim CellChange As String = DataGridView2.Rows(i).Cells("CODE").Value.ToString 'This is line 363
If CellChange.Contains(findtxt) = True Then
If Not IsDBNull(DataGridView2.Rows(i).Cells("STATUS").Value) _
AndAlso DataGridView2.Rows(i).Cells("STATUS").Value = "IN" Then
MsgBox("Ticket Used")
Exit Sub
Else
With DataGridView2
.Rows(i).Cells("STATUS").Value = "IN"
Exit Sub
End With
End If
End If
Next
End If
Catch e As Exception
MessageBox.Show(e.ToString())
End Try
'''''''''''''''''''If Flase Only Works Here''''''''''''''''''''''
Try
If DataGridView2.Rows.Count > 0 Then
For i As Integer = 0 To DataGridView2.Rows.Count - 1
Dim CellChange As String = DataGridView2.Rows(i).Cells("CODE").Value.ToString
If CellChange.Contains(findtxt) = False Then
MsgBox("InValid Ticket")
Exit Sub
End If
Next
End If
Catch e As Exception
MessageBox.Show(e.ToString())
End Try
End Sub
the problem is i keep getting the error MSGBOX
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.