vb.net: column names using recordset as Odbc.OdbcDataReader - vb.net

I'm creating a Web Service that retrive data from postgres DB.
Here my code:
Dim sql As String
Dim recordSet As Odbc.OdbcDataReader
Dim command As Odbc.OdbcCommand
Dim ret As New DataOutput
Dim dataLst As New List(Of Data)
Dim element As Dati
sql = "SELECT * from demo.table"
command = New Odbc.OdbcCommand(sql, odbcConn)
Try
recordSet = command.ExecuteReader
While recordSet.Read()
element = New Data
element.id = recordSet(0)
element.name = recordSet(1)
element.description = recordSet(2)
element.address = recordSet(3)
dataLst.Add(element)
End While
ret.arrDati = dataLst
This only show me rows value but I need column names too.
How can i do this?

You can access the column names with the GetName method:
Dim sql As String
Dim recordSet As Odbc.OdbcDataReader
Dim command As Odbc.OdbcCommand
Dim ret As New DataOutput
Dim dataLst As New List(Of Data)
Dim element As Dati
sql = "SELECT * from demo.table"
command = New Odbc.OdbcCommand(sql, odbcConn)
Try
recordSet = command.ExecuteReader
While recordSet.Read()
element = New Data
element.id = recordSet(0) 'column name: recordSet.GetName(0)
element.name = recordSet(1) 'column name: recordSet.GetName(1)
element.description = recordSet(2) 'column name: recordSet.GetName(2)
element.address = recordSet(3) 'column name: recordSet.GetName(3)
dataLst.Add(element)
End While
ret.arrDati = dataLst

Related

adding multiple text files to gridview (devexpress) in vb.net

I have a folder with multiple text files in it, each text files has about 14 lines of text.
I would like to add all text files in that folder to a gridcontrol/gridview in vb.net.
My current code only adds 1 text file instead of adding all. any help would be greatly appreciated.
Dim path As String = "C:\Plan\"
For Each i As String In System.IO.Directory.GetFiles(path)
Dim a, b, c As String
a = System.IO.Path.GetFileNameWithoutExtension(i)
b = System.IO.Path.GetFileName(i)
c = System.IO.Path.GetFullPath(i)
Dim LINE_pair As String = IO.File.ReadLines(i).ElementAtOrDefault(0)
Dim LINE1_details As String = IO.File.ReadLines(i).ElementAtOrDefault(1)
Dim LINE2_outlookcombo As String = IO.File.ReadLines(i).ElementAtOrDefault(2)
Dim LINE3_rsicombo As String = IO.File.ReadLines(i).ElementAtOrDefault(3)
Dim LINE4_macdcombo As String = IO.File.ReadLines(i).ElementAtOrDefault(4)
Dim LINE4_ratio As String = IO.File.ReadLines(i).ElementAtOrDefault(5)
Dim LINE5_pattern As String = IO.File.ReadLines(i).ElementAtOrDefault(6)
Dim LINE6_none As String = IO.File.ReadLines(i).ElementAtOrDefault(7)
Dim LINE7_timeframecomvo As String = IO.File.ReadLines(i).ElementAtOrDefault(8)
Dim LINE7_date As String = IO.File.ReadLines(i).ElementAtOrDefault(9)
Dim LINE8_trade As String = IO.File.ReadLines(i).ElementAtOrDefault(10)
Dim LINE9_currentprice As String = IO.File.ReadLines(i).ElementAtOrDefault(11)
Dim LINE10_tp As String = IO.File.ReadLines(i).ElementAtOrDefault(12)
Dim LINE11_sl As String = IO.File.ReadLines(i).ElementAtOrDefault(13)
Dim NewItem As New ListViewItem(a)
Dim dt As New DataTable()
dt.Columns.AddRange(New DataColumn(13) {New DataColumn("Pair"), New DataColumn("Outlook"), New DataColumn("RSI"), New DataColumn("MACD"), New DataColumn("Pattern"), New DataColumn("Misc"), New DataColumn("Rato"), New DataColumn("Time Frame"), New DataColumn("Date"), New DataColumn("File name"), New DataColumn("Trade Status"), New DataColumn("CP"), New DataColumn("TP"), New DataColumn("SL")})
dt.Rows.Add(New String() {LINE_pair, LINE2_outlookcombo, LINE3_rsicombo, LINE4_macdcombo, LINE5_pattern, LINE6_none, LINE4_ratio, LINE7_timeframecomvo, LINE7_date, a, LINE8_trade, LINE9_currentprice, LINE10_tp, LINE11_sl})
GridControl1.DataSource = dt
It is not necessary to declare the DataColumn array explicitly. It is created internally from the items in the braces.
You are throwing away your NewItem on each iteration. Why not add them to a list and add them all at once to a ListView.
You are reading the file over and over as you assign the LINE_ data. Read it once and use the resulting lines array.
You never use b and c in this code so I deleted them
I tested in with a .net DataGridView. The file io methods and the DataTable are the same.
Private Sub OPCode()
Dim path As String = "C:\Plan\"
Dim dt As New DataTable()
Dim lstListViewItems As New List(Of ListViewItem)
dt.Columns.AddRange({New DataColumn("Pair"), New DataColumn("Outlook"), New DataColumn("RSI"), New DataColumn("MACD"), New DataColumn("Pattern"), New DataColumn("Misc"), New DataColumn("Rato"), New DataColumn("Time Frame"), New DataColumn("Date"), New DataColumn("File name"), New DataColumn("Trade Status"), New DataColumn("CP"), New DataColumn("TP"), New DataColumn("SL")})
For Each i As String In System.IO.Directory.GetFiles(path)
Dim a = System.IO.Path.GetFileNameWithoutExtension(i)
Dim lines = File.ReadLines(i)
Dim LINE_pair As String = lines.ElementAtOrDefault(0)
Dim LINE1_details As String = lines.ElementAtOrDefault(1)
Dim LINE2_outlookcombo As String = lines.ElementAtOrDefault(2)
Dim LINE3_rsicombo As String = lines.ElementAtOrDefault(3)
Dim LINE4_macdcombo As String = lines.ElementAtOrDefault(4)
Dim LINE4_ratio As String = lines.ElementAtOrDefault(5)
Dim LINE5_pattern As String = lines.ElementAtOrDefault(6)
Dim LINE6_none As String = lines.ElementAtOrDefault(7)
Dim LINE7_timeframecomvo As String = lines.ElementAtOrDefault(8)
Dim LINE7_date As String = lines.ElementAtOrDefault(9)
Dim LINE8_trade As String = lines.ElementAtOrDefault(10)
Dim LINE9_currentprice As String = lines.ElementAtOrDefault(11)
Dim LINE10_tp As String = lines.ElementAtOrDefault(12)
Dim LINE11_sl As String = lines.ElementAtOrDefault(13)
dt.Rows.Add({LINE_pair, LINE2_outlookcombo, LINE3_rsicombo, LINE4_macdcombo, LINE5_pattern, LINE6_none, LINE4_ratio, LINE7_timeframecomvo, LINE7_date, a, LINE8_trade, LINE9_currentprice, LINE10_tp, LINE11_sl})
Dim NewItem As New ListViewItem(a)
lstListViewItems.Add(NewItem)
Next
ListView1.Items.AddRange(lstListViewItems.ToArray)
DataGridView1.DataSource = dt
End Sub

Read the Response and stored to database using Microsoft SMO (Server Management Objects)

Im trying to call to an URL
And than i will get response into XML format and based what Response i will get it will create Tables successfully into database using Microsoft SMO (Server Management Objects) which Allowing me to create and generate databases and tables. but for some reason it coludnt insert any data to tables and they are NULL Screenshot
XML:
<ICECAT-interface xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://data.icecat.biz/xsd/files.index.xsd">
<files.index Generated="20200219011050">
<file path="export/freexml.int/EN/1424.xml" Product_ID="1424" Updated="20200218012414" Quality="ICECAT" Supplier_id="1" Prod_ID="C4811A" Catid="846" On_Market="1" Model_Name="11" Product_View="513730" HighPic="http://images.icecat.biz/img/gallery/1424_6912543175.jpg" HighPicSize="2478427" HighPicWidth="2598" HighPicHeight="3276" Date_Added="20051023000000" Limited="No" >
<M_Prod_ID Supplier_id="11" Supplier_name="Cisco">C4811A</M_Prod_ID>
<M_Prod_ID>Tempcomp3109</M_Prod_ID>
<Country_Markets>
<Country_Market Value="NL"/>
<Country_Market Value="BE"/>
<Country_Market Value="FR"/>
<Country_Market Value="UA"/>
<Country_Market Value="GB"/>
<Country_Market Value="DE"/>
<Country_Market Value="BG"/>
</Country_Markets>
</file>
</files.index>
</ICECAT-interface>
Module:
Class Module1
Public Shared Sub Main()
Dim url As String = "http://data.Icecat.biz/export/freexml/EN/daily.index.xml"
ProcessXMLFeedURL(url)
End Sub
Public Shared Function ProcessXMLFeedURL(MyURL As String) As Boolean
Dim OK As Boolean = False
Try
Dim rssReq As WebRequest = WebRequest.Create(MyURL)
Dim username As String = ""
Dim password As String = ""
Dim encoded As String = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password))
rssReq.Headers.Add("Authorization", "Basic " + encoded)
'//Get the WebResponse
Dim rep As WebResponse = rssReq.GetResponse()
'//Read the Response in a XMLTextReader
Dim xtr As XmlTextReader = New XmlTextReader(rep.GetResponseStream())
'// Set up the connection to the SQL server
Dim MyConnectionString As String = "Data Source=......"
Dim Connection As SqlConnection = New SqlConnection(MyConnectionString)
Dim MyServer As Server = New Server(New ServerConnection(Connection))
Dim db As Database = New Database(MyServer, "xxxxx")
db.Create()
'//Create a new DataSet
Dim ds As DataSet = New DataSet()
'//Read the Response into the DataSet
ds.ReadXml(xtr)
'// Parse tables
For i As Integer = 0 To ds.Tables.Count - 1
Dim Mytable As Table
Dim MyTableName As String = ds.Tables(i).TableName
If Not HaveTable(MyConnectionString, MyTableName) Then
'// Create the table
Try
Mytable = New Table(db, MyTableName)
Catch ex As Exception
Dim ii As Integer = 0
End Try
'// Create the columns
Dim Mycolumn As Column = New Column()
For Each dc As DataColumn In ds.Tables(i).Columns
Mycolumn = New Column(Mytable, dc.ColumnName)
Mycolumn.DataType = getdatatype(dc.DataType.ToString)
Mytable.Columns.Add(Mycolumn)
Next
Mytable.Create()
Dim PrimaryKeys() As DataColumn = ds.Tables(i).PrimaryKey
Dim PrimaryKey As DataColumn
For Each PrimaryKey In PrimaryKeys
Dim Myindex As Index = New Index(Mytable, PrimaryKey.ColumnName)
Myindex.IndexKeyType = IndexKeyType.DriPrimaryKey
Myindex.IndexedColumns.Add(New IndexedColumn(Myindex, PrimaryKey.ColumnName))
Mytable.Indexes.Add(Myindex)
Next
End If
Using MyConnection As SqlConnection = New SqlConnection(MyConnectionString)
MyConnection.Open()
Using bulkcopy As SqlBulkCopy = New SqlBulkCopy(MyConnection)
bulkcopy.DestinationTableName = "[" & MyTableName & "]"
Try
bulkcopy.WriteToServer(ds.Tables(i))
Catch ex As Exception
Dim iw As Integer = 0
End Try
End Using
MyConnection.Close()
End Using
Next
Catch ex As Exception
Throw ex '// Do errorhanddling here
End Try
Return OK
End Function
Shared Function getdatatype(Mydatatype As String) As DataType
Dim dty As DataType = Nothing
Select Case Mydatatype
Case Is = "System.Decimal"
dty = DataType.Decimal(2, 18)
Case Is = "System.String"
dty = DataType.VarChar(500)
Case Is = "System.Int32"
dty = DataType.Int
End Select
Return dty
End Function
Shared Function HaveTable(MyConnectionString As String, TableName As String) As Boolean
Dim OK As Boolean = False
Try
Dim dbConn As New SqlConnection(MyConnectionString)
dbConn.Open()
Dim restrictions(3) As String
restrictions(2) = TableName
Dim dbTbl As DataTable = dbConn.GetSchema("Tables", restrictions)
If dbTbl.Rows.Count > 0 Then
OK = True
End If
dbTbl.Dispose()
dbConn.Close()
dbConn.Dispose()
Catch ex As Exception
Dim ss As Integer = 0
End Try
Return OK
End Function
End Class
Can anyone please help me!

Linq from CSV source return empty record on VB.net

I have data extract from csv using vb.net as below code
Dim district As New List(Of tbDistrict)
Dim path As String = AppDomain.CurrentDomain.BaseDirectory & "tb_district.csv"
Dim results = (From line In File.ReadAllLines(path)
Let value = line.Split(";").
Select(Function(x) x)
Select New With {.district_id = value(0),
.district_code = value(1),
.amphur_id = value(2),
.district_name = value(3),
.province_id = value(4)}).ToList()
'Console.WriteLine(results.Count)
For Each item In results
district.Add(New tbDistrict With {
.district_id = item.district_id,
.district_code = item.district_code,
.district_name = item.district_name,
.amphur_id = item.amphur_id,
.province_id = item.province_id
})
Next
I have 2000 records add to list. Then I try to use linq to get some record by using below code
Dim provinceid As String = "1"
Dim amphurid As String = "1"
Dim mystring As String = "test"
Dim searchtabbol As List(Of tbDistrict) = district.Where(Function(x) _
(x.province_id = provinceid) AndAlso
(x.amphur_id = amphurid) AndAlso
(x.district_name.Contains(mystring.Trim()))).ToList()
Console.WriteLine(searchtabbol.Count)
But I get 0 record return although row exist. I'm not sure what's wrong in code?. Appreciated for all advise.

Make data in a particular col as link in vb.net

I have a datagrid view that gets the data from oracle database using this code.
Dim UpperCase As String = UCase(Instance_NameTextBox.Text)
Dim sql As String = "select instance_name,application_url from INSTANCE_DETAILS where upper(INSTANCE_NAME) like '%" + UpperCase + "%'"
Dim ds As New DataSet
Dim da As New OracleDataAdapter(sql, conn)
da.Fill(ds, "TEST")
DataGridView1.DataSource = ds.Tables(0)
I need the second column of the view to come as link that opens the url in browser.Any help?
First you need to create a TemplateColumn
TemplateField myTemplate = new TemplateField();
myTemplate.HeaderText = "MyLinkButton";
MainGridView.Columns.Add(myTemplate);
GridView.DataSource = GetData(); \\Your data source here
GridView.DataBind();
Then In your GridView RowDataBound event
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink myLink = new HyperLink ();
myLink.ID = "HyperLink1";
myLink.Text = "Click here";
myLink.NavigateUrl = e.Row.Cells[1].Value.ToString();
e.Row.Cells[1].Controls.Add(myLink);
}
}
Got it working using the following code.
Dim col As New DataGridViewLinkColumn
Dim sql As String = "select * from INSTANCE_DETAILS where upper(INSTANCE_NAME) like '%" + UpperCase + "%'"
Dim ds As New DataSet
Dim da As New OracleDataAdapter(sql, conn)
da.Fill(ds, "TEST")
DataGridView1.DataSource = ds.Tables(0)
Dim obj As New DataGridViewRow
Dim Data As String
Follwing is to change it for each row which takes the data from the 3rd col.
Dim i As Integer
i = 0
Dim x As Integer
x = DataGridView1.RowCount
For Each obj In DataGridView1.Rows
If i < x - 1 Then
Data = ds.Tables(0).Rows(i)(3).ToString()
DataGridView1.Rows(i).Cells("Links").Value = Data
i = i + 1
End If
Next obj

how to add new row after filling all textboxes, not replace old row in gridview?

i wrote program in vb.net. in my page, i have 3 textbox. in Txt_CardBarcode_TextChanged ,i wrote this codes:
Try
Dim stream_CardBarcode As System.IO.MemoryStream = New System.IO.MemoryStream
Dim cls As New Cls_Barcode
Dim pic_CardBarcode As System.Drawing.Image = Nothing
cls.btnEncode(pic_CardBarcode, Txt_CardBarcode.Text.Trim)
pic_CardBarcode.Save(stream_CardBarcode, System.Drawing.Imaging.ImageFormat.Png)
Dim f_cardBarcode As IO.FileStream = _
New IO.FileStream("C:\fafa.png", IO.FileMode.Create, IO.FileAccess.ReadWrite)
Dim b_cardBarcode As Byte() = stream_CardBarcode.ToArray
f_cardBarcode.Write(b_cardBarcode, 0, b_cardBarcode.Length)
f_cardBarcode.Close()
Dim ds As DS_Test
ds = New DS_Test
Dim Val_LabelBarcode() = {stream_CardBarcode.ToArray, Txt_ICCID.Text.Trim}
ds.Tables(2).Rows.Add(Val_LabelBarcode)
crp_CardBarcode.SetDataSource(ds.Tables(2))
Dim frm_CrpCardBarcode As New Frm_RepCardBarcode
frm_CrpCardBarcode.CrystalReportViewer1.ReportSource = crp_CardBarcode
GVSimInfo.DataSource = ds.Tables(2)
ds.Tables(2).Rows.Add(1)
GVSimInfo.Rows(GVSimInfo.Rows.Count - 1).Cells(0).Value = True
ds.Tables(2).Rows(0).Item(0) = True
ds.Tables(2).Rows(0).Item(1) = ""
ds.Tables(2).Rows(0).Item(2) = Txt_ICCID.Text
ds.Tables(2).Rows(0).Item(3) = ""
ds.Tables(2).Rows(0).Item(4) = ""
now, in run time, after filling 3textbox, new row add to gridview , but when user want to more than filling textboxes, new row in grid view replace on old row!!!
how to set new row add to grid view , instead of replace old row?
in my dataset, i put 3tables. tables(2) has 2 columns that save image barcode with byte array data type, but in my gridview ,i have 5 columns.
in run time give me error dialog,it is images from it:
If your DGV is not bound to any data Source:
GVSimInfo.Rows.Add(1);
If your DGV is bound to some Data Source then :
ds.Tables(2).Rows.Add(1)
Add this code after your last text box is filled and new row is needed.
to set the values you can use :
ds.Tables(2).Rows(0).Item("Column_number") = "your text"
Try
Dim stream_CardBarcode As System.IO.MemoryStream = New System.IO.MemoryStream
Dim cls As New Cls_Barcode
Dim pic_CardBarcode As System.Drawing.Image = Nothing
cls.btnEncode(pic_CardBarcode, Txt_CardBarcode.Text.Trim)
pic_CardBarcode.Save(stream_CardBarcode, System.Drawing.Imaging.ImageFormat.Png)
Dim f_cardBarcode As IO.FileStream = _
New IO.FileStream("C:\fafa.png", IO.FileMode.Create, IO.FileAccess.ReadWrite)
Dim b_cardBarcode As Byte() = stream_CardBarcode.ToArray
f_cardBarcode.Write(b_cardBarcode, 0, b_cardBarcode.Length)
f_cardBarcode.Close()
Dim ds As DS_Test
ds = New DS_Test
Dim Val_LabelBarcode() = {stream_CardBarcode.ToArray, Txt_ICCID.Text.Trim}
ds.Tables(2).Rows.Add(Val_LabelBarcode)
crp_CardBarcode.SetDataSource(ds.Tables(2))
Dim frm_CrpCardBarcode As New Frm_RepCardBarcode
frm_CrpCardBarcode.CrystalReportViewer1.ReportSource = crp_CardBarcode
ds.Tables(2).Rows.Add(1)
GVSimInfo.Rows(GVSimInfo.Rows.Count - 1).Cells(0).Value = True
ds.Tables(2).Rows(0).Item(0) = True
ds.Tables(2).Rows(0).Item(1) = ""
ds.Tables(2).Rows(0).Item(2) = Txt_ICCID.Text
ds.Tables(2).Rows(0).Item(3) = ""
ds.Tables(2).Rows(0).Item(4) = ""
GVSimInfo.DataSource = ds.Tables(2) <-------