VB service export SQL to CSV - vb.net

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

Related

How to generate all combinations of partitioning a string in VB.Net

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

More efficient method for string parsing?

First part of the code is to retrieve data from the web. It takes only a part of the second to complete the request. Second part of the code is to split data so that parts of data can be shown in different labels and it takes around 5-6 second to complete this operation?
Why is that? Can it be done faster?
First part of the code (textbox1 key down event)
If e.KeyCode = Keys.Enter Then
TextBox1.Text = UCase(TextBox1.Text)
If TextBox1.Text = "" Then
GoTo exx
Else
Dim strURL As String
Dim strSymbol As String = TextBox1.Text
strURL = " http://quote.yahoo.com/d/quotes.csv?" & _
"s=" & strSymbol & _
"&d=t" & _
"&f=snl1pmwvj1l1"
MessageBox.Show(RequestWebData(strURL))
Second part of the code and functions :
Label24.Text = (GetName2(RequestWebData(strURL), 3))
Dim myText = Label24.Text
Dim dIndex = myText.IndexOf("Inc.")
If (dIndex > -1) Then
Label24.Text = (Strings.Left(Label24.Text, dIndex + 4))
Else
Label24.Text = (Label24.Text)
End If
Dim myText2 = Label24.Text
Dim dIndex2 = myText2.IndexOf("Common")
If (dIndex2 > -1) Then
Label24.Text = (Label24.Text.Replace("Common", ""))
Else
Label24.Text = (Label24.Text)
End If
Label6.Text = (GetName(RequestWebData(strURL), 4))
Label6.Text = (GetName3(Label6.Text, 1))
Label6.Text = FormatNumber(Label6.Text, 2)
Label17.Text = (GetName(RequestWebData(strURL), 5))
Label21.Text = (GetName(RequestWebData(strURL), 7))
Dim x As String = GetName(RequestWebData(strURL), 8)
Label30.Text = GetName3(x, 1)
Label30.Text = FormatNumber(Label30.Text, 0)
Label32.Text = GetName3(x, 2)
TextBox2.Focus()
Function GetName(ByVal LineIn As String, ByVal i As Integer) As String
'Dim x As Integer
Return LineIn.Split(""",")(i)
End Function
Function GetName2(ByVal LineIn As String, ByVal i As Integer) As String
'Dim x As Integer
Return LineIn.Split("""")(i)
End Function
Function GetName3(ByVal LineIn As String, ByVal i As Integer) As String
'Dim x As Integer
Return LineIn.Split(",")(i)
End Function
Maybe it is so slow because of these three functions that I am using to split data?

vb.net - Why do I get this error when trying to bubble sort a csv file?

I have a csv file which I'm trying to sort by data (numerical form)
The csv file:
date, name, phone number, instructor name
1308290930,jim,041231232,sushi
123123423,jeremy,12312312,albert
The error I get is: Conversion from string "jeremy" to type 'double'is not valid
Even though no where in my code I mention double...
My code:
Public Class Form2
Dim currentRow As String()
Dim count As Integer
Dim one As Integer
Dim two As Integer
Dim three As Integer
Dim four As Integer
'concatenation / and operator
'casting
Dim catchit(100) As String
Dim count2 As Integer
Dim arrayone(4) As Decimal
Dim arraytwo(4) As String
Dim arraythree(4) As Decimal
Dim arrayfour(4) As String
Dim array(4) As String
Dim bigstring As String
Dim builder As Integer
Dim twodata As Integer
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("D:\completerecord.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
Dim count As Integer
Dim currentField As String
count = 0
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
For Each currentField In currentRow
' makes one array to contain a record for each peice of text in the file
'MsgBox(currentField) '- test of Field Data
' builds a big string with new line-breaks for each line in the file
bigstring = bigstring & currentField + Environment.NewLine
'build two arrays for the two columns of data
If (count Mod 2 = 1) Then
arraytwo(two) = currentField
two = two + 1
'MsgBox(currentField)
ElseIf (count Mod 2 = 0) Then
arrayone(one) = currentField
one = one + 1
ElseIf (count Mod 2 = 2) Then
arraythree(three) = currentField
three = three + 1
ElseIf (count Mod 2 = 3) Then
arrayfour(four) = currentField
four = four + 1
End If
count = count + 1
'MsgBox(count)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Error Occured, Please contact Admin.")
End Try
End While
End Using
RichTextBox1.Text = bigstring
' MsgBox("test")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim NoMoreSwaps As Boolean
Dim counter As Integer
Dim Temp As Integer
Dim Temp2 As String
Dim listcount As Integer
Dim builder As Integer
Dim bigString2 As String = ""
listcount = UBound(arraytwo)
'MsgBox(listcount)
builder = 0
'bigString2 = ""
counter = 0
Try
'this should sort the arrays using a Bubble Sort
Do Until NoMoreSwaps = True
NoMoreSwaps = True
For counter = 0 To (listcount - 1)
If arraytwo(counter) > arraytwo(counter + 1) Then
NoMoreSwaps = False
If arraytwo(counter + 1) > 0 Then
Temp = arraytwo(counter)
Temp2 = arrayone(counter)
arraytwo(counter) = arraytwo(counter + 1)
arrayone(counter) = arrayone(counter + 1)
arraytwo(counter + 1) = Temp
arrayone(counter + 1) = Temp2
End If
End If
Next
If listcount > -1 Then
listcount = listcount - 1
End If
Loop
'now we need to output arrays to the richtextbox first we will build a new string
'and we can save it to a new sorted file
Dim FILE_NAME As String = "D:\sorted.txt"
'Location of file^ that the new data will be saved to
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
'If D:\sorted.txt exists then enable it to be written to
While builder < listcount
bigString2 = bigString2 & arraytwo(builder) & "," & arrayone(builder) + Environment.NewLine
objWriter.Write(arraytwo(builder) & "," & arrayone(builder) + Environment.NewLine)
builder = builder + 1
End While
RichTextBox2.Text = bigString2
objWriter.Close()
MsgBox("Text written to log file")
Else
MsgBox("File Does Not Exist")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
I think in this line is the problem
arrayone(one) = currentField
Here it trys to cast the string to a double. You have to use something like this:
arrayone(one) = Double.Parse(currentField)
or to have it a saver way:
Dim dbl As Double
If Double.TryParse(currentField, dbl) Then
arrayone(one) = dbl
Else
arrayone(one) = 0.0
End If

Finding String of Substring in VB without using library function

I am little bit confused in this program.
I am new to Visual Basic but intermediate to C.
Actually I want to get sub-string of string without using library function of Visual Basic.
Here is the C source code I also given my VB code too.
1.The Program will get two inputs from user i.e A & B
2. Than Find the substring from B.
3. Finally Print the result.
int i,j=0,k=0,substr=0;
for(i=0;i<strlen(a);i++)
{
if(a[i]==b[j])
{
j++;
if(b[j]==0)
{
printf("second string is substring of first one");
substr=1;
break;
}
}
}
for(i=0;i<strlen(b);i++)
{
if(b[i]==a[k])
{
k++;
if(a[k]==0)
{
printf(" first string is substring of second string");
substr=1;
break ;
}
}
}
if(substr==0)
{
printf("no substring present");
}
While my code is
Dim a As String
Dim b As String
a = InputBox("Enter First String", a)
b = InputBox("Enter 2nd String", b)
Dim i As Integer
Dim j As Integer = 0
Dim k As Integer = 0
Dim substr As Integer = 0
For i = 0 To a.Length - 1
If a(i) = b(j) Then
j += 1
If b(j) = 0 Then
MsgBox("second string is substring of first one")
substr = 1
Exit For
End If
End If
Next i
For i = 0 To b.Length - 1
If b(i) = a(k) Then
k += 1
If a(k) = 0 Then
MsgBox(" first string is substring of second string")
substr = 1
Exit For
End If
End If
Next i
If substr = 0 Then
MsgBox("no substring present")
End If
End Sub
While compiling it gives following debugging errors.
Line Col
Error 1 Operator '=' is not defined for types 'Char' and 'Integer'. 17 24
Error 2 Operator '=' is not defined for types 'Char' and 'Integer'. 27 24
Part of your confusion is that .Net strings are much more than just character buffers. I'm going to assume that you can at least use strings. If you can't, use need to declare character arrays instead. That out of the way, this should get you there as a 1:1 translation:
Private Shared Function search(ByVal a As String, ByVal b As String) As Integer
Dim i As Integer = 0
Dim j As Integer = 0
Dim firstOcc As Integer
While i < a.Length
While a.Chars(i)<>b.Chars(0) AndAlso i < a.Length
i += 1
End While
If i >= a.Length Then Return -1 'search can not continue
firstOcc = i
While a.Chars(i)=b.Chars(j) AndAlso i < a.Length AndAlso j < b.Length
i += 1
j += 1
End While
If j = b.Length Then Return firstOcc
If i = a.Length Then Return -1
i = firstOcc + 1
j = 0
End While
Return 0
End Function
Shared Sub Main() As Integer
Dim a As String
Dim b As String
Dim loc As Integer
Console.Write("Enter the main string :")
a = Console.ReadLine()
Console.Write("Enter the search string :")
b = Console.ReadLine()
loc = search(a, b)
If loc = -1 Then
Console.WriteLine("Not found")
Else
Console.WriteLine("Found at location {0:D}",loc+1)
End If
Console.ReadKey(True)
End Sub
But please don't ever actually use that. All you really need is this:
Private Shared Function search(ByVal haystack as String, ByVal needle As String) As Integer
Return haystack.IndexOf(needle)
End Function
VB has a built-in function called InStr, it's part of the language. It returns an integer specifying the start position of the first occurrence of one string within another.
http://msdn.microsoft.com/en-us/library/8460tsh1(v=VS.80).aspx
Pete
Try this one, this will return a List(Of Integer) containing the index to all occurrence's of the find text within the source text, after the specified search starting position.
Option Strict On
Public Class Form1
''' <summary>
''' Returns an array of indexes where the find text occurred in the source text.
''' </summary>
''' <param name="Source">The text you are searching.</param>
''' <param name="Find">The text you are searching for.</param>
''' <param name="StartIndex"></param>
''' <returns>Returns an array of indexes where the find text occurred in the source text.</returns>
''' <remarks></remarks>
Function FindInString(Source As String, Find As String, StartIndex As Integer) As List(Of Integer)
If StartIndex > Source.Length - Find.Length Then Return New List(Of Integer)
If StartIndex < 0 Then Return New List(Of Integer)
If Find.Length > Source.Length Then Return New List(Of Integer)
Dim Results As New List(Of Integer)
For I = StartIndex To (Source.Length) - Find.Length
Dim TestString As String = String.Empty
For II = I To I + Find.Length - 1
TestString = TestString & Source(II)
Next
If TestString = Find Then Results.Add(I)
Next
Return Results
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim Search As String = "Hello world, this world is an interesting world"
Dim Find As String = "world"
Dim Indexes As List(Of Integer) = New List(Of Integer)
Try
Indexes = FindInString(Search, Find, 0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
RichTextBox1.Text = "Search:" & vbCrLf
RichTextBox1.Text = RichTextBox1.Text & Search & vbCrLf & vbCrLf
RichTextBox1.Text = RichTextBox1.Text & "Find:" & vbCrLf
RichTextBox1.Text = RichTextBox1.Text & Find & vbCrLf & vbCrLf
RichTextBox1.Text = RichTextBox1.Text & "-----------" & vbCrLf
RichTextBox1.Text = RichTextBox1.Text & "Result Indexes:" & vbCrLf & vbCrLf
For Each i As Integer In Indexes
RichTextBox1.Text = RichTextBox1.Text & i.ToString & vbCr
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
Here is another way, where there is no use of .Net functions.
Function FindInString(Source As String, Find As String, StartIndex As Integer) As Integer()
If StartIndex > Len(Source) - Len(Find) Then Return {}
If StartIndex < 0 Then Return {}
If Len(Find) > Len(Source) Then Return {}
Dim Results As Integer() = {}, ResultCount As Integer = -1
For I = StartIndex To Len(Source) - Len(Find)
Dim TestString As String = ""
For II = I To I + Len(Find) - 1
TestString = TestString & Source(II)
Next
If TestString = Find Then
ResultCount += 1
ReDim Preserve Results(ResultCount)
Results(ResultCount) = I
End If
Next
Return Results
End Function

Name Proper Casing

Can you help me in having a proper casing,
I have this code...
Private Function NameCsing(ByVal sValue As String) As String
Dim toConvert As String() = sValue.Split(" ")
Dim lst As New List(Of String)
For i As Integer = 0 To toConvert.Length - 1
Dim converted As String = ""
If toConvert(i).Contains("~") Then
Dim toName As String() = toConvert(i).Split("~")
Dim sName As String = ""
For n As Integer = 0 To toName.Length - 1
Dim sconvert As String = ""
If n = 0 Then
sName = StrConv(toName(n), VbStrConv.ProperCase)
Else
sName += StrConv(toName(n), VbStrConv.ProperCase)
End If
Next
converted = sName
Else
converted = toConvert(i)
End If
lst.Add(converted)
Next
Dim ret As String = ""
For i As Integer = 0 To lst.Count - 1
If i = 0 Then
ret = lst(0)
Else
ret += " " + lst(i)
End If
Next
Return ret
End Function
My codes will just output like this "McDonalds" is you input "mc~donalds"
now my problem is eh I input "evalue", my output must be "eValue"
The only way to know how to treat a special string is to code it yourself from a list of rules:
Private Function NameCsing(ByVal sValue As String) As String
If sValue.Trim.ToLower = "evalue" Then Return "eValue"
'Then process any other special cases
End Function