How to return a string from a text file with condition met? - vb.net

Public Sub openDB()
Dim Lines As New List(Of String)
Try
' Open the file using a stream reader.
Using sr As New StreamReader("Config.txt")
Dim line As String
' Read the stream to a string and write the string to the console.
line = sr.ReadLine()
Do Until String.IsNullOrEmpty(line)
Lines.Add(line)
line = sr.ReadLine
Loop
End Using
Catch e As Exception
Console.WriteLine("The file could not be read:")
Console.WriteLine(e.Message)
End Try
Dim dbname As String = g_DatabaseName
Dim server As String = Lines.Where(Function(str) str.Contains("server =")).ToString
Dim user As String = ""
Dim password As String = ""
conn = New MySqlConnection
conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false; Convert Zero Datetime=True", server, user, password, dbname)
conn.Open()
End Sub
Im try to return some string from a text file, so I use StreamReader to read the file and store them into a list. Now I try to declare a variable to get "localhost" from list of string, but the code below is not work for me.
Dim server As String = Lines.Where(Function(str) str.Contains("server
=")).ToString

Enumerable.Where does not return a single string but possibly multiple, using ToString gives you not the first matching line but just the name of the type which is System.Linq.Enumerable+WhereArrayIterator1[System.String].
Either declare it as IEnumerable(Of String) or use First/ FirstOrDefault to get the first line that matches the condition:
Dim serverLine As String = Lines
.Where(Function(str) str.Contains("server ="))
.FirstOrDefault()
You can also use the overload of FirstOrDefault(Nothing if there was no such line):
Dim serverLine As String = Lines.FirstOrDefault(Function(str) str.Contains("server ="))
To extract Localhost:
Dim server As String = serverLine.Substring(serverLine.IndexOf("server =") + "server =".Length).Trim(""""c, " "c)

Related

How to convert encoding of FTP Getlisting array of strings?

I am using the following vb code to get the list of files in a ftp directory and populate a database table with it to be used in another integration process. Please forgive my bad bad programming skills (I am not a vb.net developer).
Public Sub Main()
Dim StrFolderArrary As String() = Nothing
Dim StrFileArray As String() = Nothing
Dim fileName As String
Dim RemotePath As String
RemotePath = Dts.Variables("User::FTPFullPath").Value.ToString()
Dim ADODBConnection As SqlClient.SqlConnection
ADODBConnection = DirectCast(Dts.Connections("DB_Connection").AcquireConnection(Dts.Transaction), SqlClient.SqlConnection)
Dim cm As ConnectionManager = Dts.Connections("FTP_Connection") 'FTP connection manager name
Dim ftp As FtpClientConnection = New FtpClientConnection(cm.AcquireConnection(Nothing))
ftp.Connect() 'Connecting to FTP Server
ftp.SetWorkingDirectory(RemotePath) 'Provide the Directory on which you are working on FTP Server
ftp.GetListing(StrFolderArrary, StrFileArray) 'Get all the files and Folders List
'If there is no file in the folder, strFile Arry will contain nothing, so close the connection.
If StrFileArray Is Nothing Then
ftp.Close()
'If Files are there, Loop through the StrFileArray arrary and insert into table
Else
For Each fileName In StrFileArray
'MessageBox.Show(fileName)
Dim SQLCommandText As String
SQLCommandText = "INSERT INTO dbo._FTPFileList ([DirName],[FileName]) VALUES (N'" + RemotePath + "', N'" + fileName + "')"
'MessageBox.Show(SQLCommandText)
Dim cmdDatabase As SqlCommand = New SqlCommand(SQLCommandText, ADODBConnection)
cmdDatabase.ExecuteNonQuery()
Next
ftp.Close()
End If
' Add your code here
'
Dts.TaskResult = ScriptResults.Success
End Sub
It works fine and I get the results in the database table. The problem is that the encoding of the strings coming from FTP makes the file names with accentuation to be written incorrectly as shown in the example below.
database table
The correct file name is Razão and I know that the db collation is correct since it can be written like this.
So I tried to convert the strings using this code for each file name in the string array but without any success.
For Each fileName In StrFileArray
Dim utf8 As UTF8Encoding = New UTF8Encoding(True, True)
Dim bytes As Byte() = New Byte(utf8.GetByteCount(fileName) + utf8.GetPreamble().Length - 1) {}
Array.Copy(utf8.GetPreamble(), bytes, utf8.GetPreamble().Length)
utf8.GetBytes(fileName, 0, fileName.Length, bytes, utf8.GetPreamble().Length)
Dim fileName2 As String = utf8.GetString(bytes, 0, bytes.Length)
I believe it is coming with different encoding from the FTP side so I would like to know how to convert the strings during the GetListing method.
Or do you have any ideas how to deal with this?
Thanks in advance.
edit:
I also tried the following code without success.
Dim utf8 As Encoding = Encoding.UTF8
Dim w1252 As Encoding = Encoding.GetEncoding(1252)
Dim w1252Bytes As Byte() = w1252.GetBytes(fileName)
Dim utf8Bytes As Byte() = Encoding.Convert(w1252, utf8, w1252Bytes)
Dim utf8Chars As Char() = New Char(utf8.GetCharCount(utf8Bytes, 0, utf8Bytes.Length) - 1) {}
utf8.GetChars(utf8Bytes, 0, utf8Bytes.Length, utf8Chars, 0)
Dim fileName2 As String = New String(utf8Chars)

Using rs.exe to run a parameter report on report server

I have a situation when I am trying to run a rs.exe to run my report (with parameter).
I am using this bat script below:
"\\server\R\subfolder\working\app\rs.exe" -i \\server\R\subfolder\working\inputfile\coo.rss -s "http://server/ReportServer_MSSQLSERVER2" -v FILENAME="\\server\R\subfolder\working\inputfile\file.csv" -v REPORTSERVER_FOLDER="/FILE_REPORT/FILE" -v Inputfile='DocType' -t -v FORMAT="EXCEL" -e Exec2005
In the above bat script (names coo.bat), I hard coded report parameter (which isInputfile='DocType) and I then referenced this in report service script below:
Public Sub Main()
Dim separators As String = " "
Dim Commands As String = Microsoft.VisualBasic.Command()
DIm inputid As string
Dim args() As String = Commands.Split(separators.ToCharArray)
Dim argcount As Integer = 0
For Each x As String In args
argcount += 1
Next
inputid = args(0).ToUpper
TRY
DIM deviceInfo as string = Nothing
DIM extension as string = Nothing
DIM encoding as string
DIM mimeType as string = "application/Excel"
DIM warnings() AS Warning = Nothing
DIM streamIDs() as string = Nothing
DIM results() as Byte
rs.Credentials = System.Net.CredentialCache.DefaultCredentials
rs.LoadReport(REPORTSERVER_FOLDER, inputid)
results = rs.Render(FORMAT, deviceInfo, extension, mimeType, encoding, warnings, streamIDs)
DIM stream As FileStream = File.OpenWrite(FILENAME)
stream.Write(results, 0, results.Length)
stream.Close()
Catch e As IOException
Console.WriteLine(e.Message)
End Try
End Sub
But, whenever I execute the coo.bat, I keep getting :Unhandled exception:The parameter value provided for 'snapshotID' does not match the parameter type.
I will appreciate your inputs.
I finally found the solution. Please see the edited code
Public Sub Main()
Dim separators As String = " "
Dim Commands As String = Microsoft.VisualBasic.Command()
Dim args() As String = Commands.Split(separators.ToString)
'Report Parameters
Dim parameters(1) As ParameterValue
parameters(0) = New ParameterValue()
parameters(0).Name = "Inputfile"
parameters(0).Value =Inputfile
TRY
DIM historyID as string = Nothing
DIM deviceInfo as string = Nothing
DIM extension as string = Nothing
DIM encoding as string
DIM mimeType as string = "application/Excel"
DIM warnings() AS Warning = Nothing
DIM streamIDs() as string = Nothing
DIM results() as Byte
rs.Credentials = System.Net.CredentialCache.DefaultCredentials
rs.LoadReport(REPORTSERVER_FOLDER,historyID )
rs.SetExecutionParameters(parameters, "en-us")
results = rs.Render(FORMAT, deviceInfo, extension, mimeType, encoding, warnings, streamIDs)
DIM stream As FileStream = File.OpenWrite(FILENAME)
stream.Write(results, 0, results.Length)
stream.Close()
Catch e As IOException
Console.WriteLine(e.Message)
End Try
End Sub

Read random txt line, split strings by : and write in textboxes

I've got two textboxes and I want make account generator which will read random line from txt file on website and write it into textboxes. So, I want to read random line(just one) from a text file, where email and password are separated by : so .txt file would look like email#site.com:password , write data before : in textbox1(email) and write data from the same line after : in textbox2.
.txt file looks like this:
email1#example.com:password1
email2#example.com:password2
email3#example.com:password3 etc....
I cannot figure out how to split this strings, any help will be appreciated, thanks anyway :)
There you go.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
tbxEmail.Text = String.Empty
tbxPassword.Text = String.Empty
Dim lines As String() = getData("URL_OF_FILE")
Dim lineCount As Integer = lines.Length
Dim randomValue As Integer = CInt(Math.Floor((lineCount) * Rnd()))
Dim line As String = lines(randomValue)
Dim parts As String() = line.Split(New Char() {":"c})
Dim email As String = parts(0)
Dim password As String = parts(1)
tbxEmail.Text = email
tbxPassword.Text = password
End Sub
Function getData(url As String) As String()
Dim client As System.Net.WebClient = New System.Net.WebClient()
Dim data As String = client.DownloadString(url)
Dim returnValue As String() = data.Split(New String() {Environment.NewLine},
StringSplitOptions.RemoveEmptyEntries)
Return returnValue
End Function
Please not that this is a synchronous request, meaning it will "freeze" your application for the duration of the request.

Issue in splitting an array of strings

I'm using webrequests to retrieve data in a .txt file that's on my dropbox using this "format".
SomeStuff
AnotherStuff
StillAnother
And i'm using this code to retrieve each line and read it:
Private Sub DataCheck()
Dim datarequest As HttpWebRequest = CType(HttpWebRequest.Create("https://dl.dropboxusercontent.com.txt"), HttpWebRequest)
Dim dataresponse As HttpWebResponse = CType(datarequest.GetResponse(), HttpWebResponse)
Dim sr2 As System.IO.StreamReader = New System.IO.StreamReader(dataresponse.GetResponseStream())
Dim datastring() As String = sr2.ReadToEnd().Split(CChar(Environment.NewLine))
If datastring(datastring.Length - 1) <> String.Empty Then
For Each individualdata In datastring
MessageBox.Show(individualdata)
Console.WriteLine(individualdata)
Next
End If
End Sub
The problem is, the output is this:
It always adds a line break (equal to " " as i see as first character on each but the first line string) after the first line like:
http://img203.imageshack.us/img203/1296/gejb.png
Why this happens? I tried also replacing the Environment.Newline with nothing like this:
Dim newstring as String = individualdata.Replace(Environment.Newline, String.Empty)
But the result was the same... what's the problem here? I tried with multiple newline strings and consts like vbnewline, all had the same result, any ideas?
You are not splitting by NewLine since you are cutting off Environment.NewLine which is a string with CChar. You just have to use the overload of String.Split that takes a String() and a StringSplitOption:
So instead of
Dim text = sr2.ReadToEnd()
Dim datastring() As String = text.Split(CChar(Environment.NewLine))
this
Dim datastring() As String = text.Split({Environment.NewLine}, StringSplitOptions.None)
I suspect that your file contains a mix of NewLine+CarriageReturn (vbCrLf) and a simple NewLine (vbLf).
If this is the case then you could create an array of the possible separators
Dim seps(2) as Char
seps(0) = CChar(vbLf)
seps(1) = CChar(vbCr)
Dim datastring() As String = sr2.ReadToEnd().Split(seps, StringSplitOptions.RemoveEmptyEntries)
The StringSplitOptions.RemoveEmptyEntries is required because a vbCrLf creates an empty string between the two separators

trouble returning datatable within a try statement

I have the following piece of code that I am using to try and rip a csv file and turn it into a datatable. My problem is that the debugger never makes it to the return statement. Everything is appending to the datatable correctly, so I know that part works. Any idea's on what I can do to trouble shoot this further. Also, if you know of a simpler way to turn a import a csv file to a datatable I'd be very interested in learning about it.
Thanks!
Public Function loadCSVTableII() As DataTable
Dim dt As New DataTable("TableII")
Dim line As String = String.Empty
Dim counter As Integer = 0
Dim reader As New StreamReader(pathTableTwo)
Try
While Not IsNothing(line)
line = reader.ReadLine()
Dim lineSep As String() = line.Split(New Char() {","c})
If Not counter = 0 Then
dt.Rows.Add(lineSep)
counter += 1
Else
For Each value As String In lineSep
dt.Columns.Add(value)
Next
counter += 1
End If
End While
'cursor never gets to this code block...
Dim primarykey(0) As DataColumn
primarykey(0) = dt.Columns("Ages")
dt.PrimaryKey = primarykey
Return dt
Catch ex As Exception
Throw
End Try
End Function
Update: It is erroring out on this line in the code.
Dim lineSep As String() = line.Split(New Char() {","c})
It say that the Object reference is not set to an instance of an object. What's weird though is that it works through the whole data table fine. Could it be that the while loop is not terminating at the end of the file?
Try changing your While loop to handle the end of stream condition. It's not very clear what the IsNothing function is doing in your code.
While Not reader.EndOfStream
line = reader.ReadLine
'// Dim lineSep As String() = line.Split(New Char() {","c})
For your line split, in VB.Net, it's simple to just do this:
Dim lineSep As String() = line.Split(",")
You can use OLEDB provider for this.
string query = "SELECT Symbol, [Name of Company], FROM [just file name with extension]";
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + [csv file path without file name] + ";" + "Extended Properties=’text;HDR=YES;’";
//create dataadapter object
OleDbDataAdapter adapter = new OleDbDataAdapter(query, connStr);
// create table
DataTable dtSymbolDetails = new DataTable("ScriptDetails");
dtSymbolDetails.Columns.Add("Symbol");
dtSymbolDetails.Columns.Add("Name of Company");
// fill the table with data using adapter
adapter.Fill(dtDetails);