retrieving whole database into dataset - asp.net

I have access db with 3 different tables,I want to load the whole database into dataset so I will be able to work with the data without load the db serval times.
all the examples of working with dataset are showing how to get part of the database using ".fill"
for example :
OleDbCommand CommandObject = new OleDbCommand ("Select * from employee");
OleDbAdapter myDataAdapter = new OleDbAdapter (null, con);
myDataAdapter.SelectCommand = CommandObject;
myDataAdapter.Fill (myDataSet, "EmployeeData");
this example load only from employee but how can I etrieve the all tables in once into dataset?
in xml for instance there is command to load all the document to dataset with:" dataset.ReadXml"
How can I achive it in access db?
Thanks for any help
Baaroz

Protected Function getDataSetAndFill(ByRef connection As OleDb.OleDbConnection,
Optional ByVal isExportSchema As Boolean = True) As DataSet
Dim myDataSet As New DataSet
Dim myCommand As New OleDb.OleDbCommand
Dim myAdapter As New OleDb.OleDbDataAdapter
myCommand.Connection = connection
'Get Database Tables
Dim tables As DataTable = connection.GetOleDbSchemaTable( _
System.Data.OleDb.OleDbSchemaGuid.Tables, _
New Object() {Nothing, Nothing, Nothing, "TABLE"})
'iterate through all tables
Dim table As DataRow
For Each table In tables.Rows
'get current table's name
Dim tableName As String = table("TABLE_NAME")
Dim strSQL = "SELECT * FROM " & "[" & tableName & "]"
Dim adapter1 As New OleDb.OleDbDataAdapter(New OleDb.OleDbCommand(strSQL, connection))
adapter1.FillSchema(myDataSet, SchemaType.Source, tableName)
'Fill the table in the dataset
myCommand.CommandText = strSQL
myAdapter.SelectCommand = myCommand
myAdapter.Fill(myDataSet, tableName)
Next
''''''''''''''''''''''''''''''''''''''
'''' Add relationships to dataset ''''
''''''''''''''''''''''''''''''''''''''
'First, get relationships names from database (as well as parent table and child table names)
Dim namesQuery As String = "SELECT DISTINCT szRelationship, szReferencedObject, szObject " & _
"FROM MSysRelationships"
Dim namesCommand As New System.Data.OleDb.OleDbCommand(namesQuery, connection)
Dim namesAdapter As New System.Data.OleDb.OleDbDataAdapter(namesCommand)
Dim namesDataTable As New DataTable
namesAdapter.Fill(namesDataTable)
'Now, get MSysRelationship from database
Dim relationsQuery As String = "SELECT * FROM MSysRelationships"
Dim command As New System.Data.OleDb.OleDbCommand(relationsQuery, connection)
Dim adapter As New System.Data.OleDb.OleDbDataAdapter(command)
Dim relationsDataTable As New DataTable
adapter.Fill(relationsDataTable)
Dim relationsView As DataView = relationsDataTable.DefaultView
Dim relationName As String
Dim parentTableName As String
Dim childTablename As String
Dim row As DataRow
For Each relation As DataRow In namesDataTable.Rows
relationName = relation("szRelationship")
parentTableName = relation("szReferencedObject")
childTablename = relation("szObject")
'Keep only the record of the current relationship
relationsView.RowFilter = "szRelationship = '" & relationName & "'"
'Declare two arrays for parent and child columns arguments
Dim parentColumns(relationsView.Count - 1) As DataColumn
Dim childColumns(relationsView.Count - 1) As DataColumn
For i As Integer = 0 To relationsView.Count - 1
parentColumns(i) = myDataSet.Tables(parentTableName). _
Columns(relationsView.Item(i)("szReferencedColumn"))
childColumns(i) = myDataSet.Tables(childTablename). _
Columns(relationsView.Item(i)("szColumn"))
Next
Dim newRelation As New DataRelation(relationName, parentColumns, childColumns, False)
myDataSet.Relations.Add(newRelation)
Next
If isExportSchema Then
Dim schemaName = GetXmlSchemaFileName()
If File.Exists(schemaName) Then File.SetAttributes(schemaName, FileAttributes.Normal)
myDataSet.WriteXmlSchema(schemaName)
End If
Return myDataSet
End Function

You should just call the OleDbDataAdapter.Fill method with different SelectCommands and pass the same DataSet but different table names inside. In this case, your dataSet will contain different filled tables.

Related

Create report dynamically using ParameterFields

I have to create crystal report dynamically by using ParameterFields. - In that a single parameter have to call particular row from MySQL database dynamically. Now I called multiple values from MySql database static and single.
I need to call particular row(dynamically) from MySQL database.
Dim sql_Sel As String
Dim hIssId As Integer = 0
Dim connectionInfo1 As New ConnectionInfo()
Dim SqlCon As String = "Data source= *****"
hIssId = Request.QueryString("patID")
Try
CrystLabl.ReportSource = Nothing
Me.SqlCon.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("xyz").ConnectionString
Me.SqlCon.Open()
Dim crystalReport As New ReportDocument()
sql_Sel = "exec DI_Details #opt=1"
Dim DA As SqlDataAdapter = New SqlDataAdapter(sql_Sel, SqlCon)
Dim DG As New DataSet
DG.DataSetName = "DataSet.xsd"
DA.Fill(DG, "DataTable1")
Dim paramFields3 As New CrystalDecisions.Shared.ParameterFields()
For Each i As String In sql_Sel
Dim paramField31 As New CrystalDecisions.Shared.ParameterField()
Dim discreteVal1 As New CrystalDecisions.Shared.ParameterDiscreteValue()
discreteVal1 = New ParameterDiscreteValue()
paramField31.ParameterFieldName = "My Parameter"
discreteVal1.Value = ((DG.Tables(0).Rows(0).Item(1)) & (DG.Tables(0).Rows(0).Item(2)) & (DG.Tables(0).Rows(0).Item(3)) >(DG.Tables(0).Rows(0).Item(6)))
paramField31.CurrentValues.Add(discreteVal1)
paramFields3.Add(paramField31)
Next
CrystLabl.ParameterFieldInfo = paramFields3
CrystLabl.ReportSource = "CrystalReport.rpt"
CrystLabl.RefreshReport()
Catch ex As Exception
Finally
End Try
End Sub

Using ViewState to apply filters on Listview

I have used ListView Control to gets list of products from database. I also stores result in viewstate . Now to apply filter from checkbox to get refined data I want to know how can I use viewState values?
e.g. If 10 Products found in Music category when page loads. Now if user apply filter(Bluetooth) then only that products should be shown which are in Music & has bluetooth..
Now It is working Like on page load Music category gets fetched Then if I check Bluetooth filter then all bluetooth products comes which are not related to music.
Private Sub shop_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim pageName As String = Me.Page.RouteData.Values("category").ToString()
if not Me.isPostback Then
Try
query = select * from products where category = '"+pageName+"'
Dim conString As String = ConfigurationManager.ConnectionStrings("conio").ConnectionString
Dim con As New MySqlConnection(conString)
Dim cmd As New MySqlCommand(query)
con.Open()
Dim da As New MySqlDataAdapter()
cmd.Connection = con
da.SelectCommand = cmd
Dim dt As New DataTable()
da.Fill(dt)
ViewState("Data") = dt
products.DataSource = dt
products.DataBind()
catHeading.Text = pageName
itemCount.Text = dt.Rows.Count.ToString
con.Close()
Catch ex As Exception
Response.Write(ex)
End Try
End If
End Sub
Filter Apply code
Private Sub priceFilter_SelectedIndexChanged(sender As Object, e As EventArgs) Handles priceFilter.SelectedIndexChanged
'buildWhereClause()
Dim price As String = priceFilter.SelectedValue.ToString()
Dim dt As DataTable = DirectCast(ViewState("Data"), DataTable)
Dim dr As DataRow() = dt.[Select]((Convert.ToString("category='") & price) + "'")
products.DataSource = dt
products.DataBind()
itemCount.Text = dt.Rows.Count.ToString
End Sub
I just want when user apply any filter then it should check from viewstate(Data) rather to entire table.
Save your category in viewstate & on Checked get that category in string & join that string in your query. something like this
Dim constr As String = ConfigurationManager.ConnectionStrings("connectionstring").ConnectionString
Dim query As String = "select * from table"
Dim joiner As String = ""
Dim condition As String = String.Empty
Dim whereClause As String = String.Empty
Dim priceCondition As String = String.Empty
Try
Dim category As String = ViewState("Data")
condition = String.Concat(condition, joiner, String.Format("{0}", category))
If joiner = "" Then joiner = ""
joiner = " where "
If Not String.IsNullOrEmpty(condition) Then
whereClause = String.Concat(whereClause, joiner, String.Format("category Like '%{0}%'", condition))
joiner = " and "
End If
'Same way you can apply multiple filters as you want & then get that in one string like below
Dim masterClause As String = String.Empty
masterClause = (query & whereClause)
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand(masterClause)
Using sda As New MySqlDataAdapter(cmd)
cmd.Connection = con
Using dt As New DataTable()
sda.Fill(dt)
products.DataSource = dt
products.DataBind()
itemCount.Text = dt.Rows.Count.ToString
End Using
End Using
End Using
End Using
For your filter you could use :
Dim dt As DataTable = DirectCast(ViewState("Data"), DataTable)
Dim dr As DataRow() = dt.Select("category='" & category & "'")
products.DataSource = dr
products.DataBind()
itemCount.Text = dr.Length

vb.net OleDbDataAdapter not working with Select From Where

If I Debug this I just get a Invalid Columnname Error("Name of the Object"). I am using a SQL database.
Protected Sub ddlKunden_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlKunden.SelectedIndexChanged
Dim strSql As String
Dim kontakt As String = ddlKunden.SelectedItem.Value
Dim dtbP As DataTable
Using connection As OleDbConnection = New OleDbConnection(strConnection)
connection.ConnectionString = strConnection
connection.Open()
'Kontaktpersonen laden
strSql = "SELECT * FROM Kontaktpersonen WHERE Nr =" & Chr(34) & kontakt & Chr(34)
dtbP = New DataTable()
Using dad As New OleDbDataAdapter(strSql, connection)
dad.Fill(dtbP)
End Using
ddlKontaktperson.Items.Clear()
ddlKontaktperson.DataSource = dtbP
ddlKontaktperson.DataTextField = "AP_Nam"
ddlKontaktperson.DataValueField = "ID"
ddlKontaktperson.DataBind()
End Using
ddlKontaktperson.Visible = True
End Sub
The Error pops at
dad.fill(dtbP)
It should select all rows Where Nr="SELECTED VALUE" and you select it in a dropdownlist. And all these rows should be saved in a Datatable then and are used in another dropdownlist.
It works when I try the exact same thing without the where.
Example:
'Kunden laden
strSql = "SELECT * FROM Kontakte"
dtbK = New DataTable()
Using dad As New OleDbDataAdapter(strSql, connection)
dad.Fill(dtbK)
End Using
ddlKunden.Items.Clear()
ddlKunden.DataSource = dtbK
ddlKunden.DataTextField = "Nr"
ddlKunden.DataValueField = "Nr"
ddlKunden.DataBind()
Please try following code
You do not need to use "'" around parameters
Just add these values as a parameter to the oledbcommand with its value and type
Otherwise, your sql command will be vulnerable to sql injection
Dim strConnection As String = "Provider=sqloledb;Data Source=(local);" &
"Initial Catalog=kodyaz;" &
"User Id=sa;Password=sa"
Dim kontakt As Int32 = 1
Dim dtbP As DataTable
Using connection As OleDbConnection = New OleDbConnection(strConnection)
connection.Open()
Dim cmd As New OleDbCommand()
cmd.Connection = connection
cmd.CommandText = "SELECT * FROM Kontaktpersonen WHERE Nr = ?"
cmd.Parameters.AddWithValue("Nr", kontakt)
dtbP = New DataTable()
Using dad As New OleDbDataAdapter(cmd)
dad.Fill(dtbP)
End Using
End Using

Invalid attempt to read when no data is present error

I have a function whose sole purpose is to fetch some data when a button is pressed and it's called multiple times. This is the function code:
Function GetData2(ByVal clientNo As Integer) As List(Of SocioInfo)
Dim theResults2 = New List(Of SocioInfo)
Dim connStr = "Data Source=localhost;Initial Catalog=testdb;Integrated Security=True;MultipleActiveResultSets=true"
Using conn = New SqlConnection(connStr)
Dim sql = "SELECT [FirstName], [LastName] FROM [CustInfo] Where ([NumCuenta] = #SocioNum)"
Dim sql2 = "SELECT [AcctName], [AcctNum], [NewAcct], [Balance] From [ACCT_NEW] Where ([AcctNum] = #SocioNum)"
Dim sqlCmd = New SqlCommand(sql, conn)
Dim sqlCmd2 = New SqlCommand(sql2, conn)
sqlCmd.Parameters.AddWithValue("#SocioNum", CDbl(txtInput.Text))
sqlCmd2.Parameters.AddWithValue("#SocioNum", CDbl(txtInput.Text))
conn.Open()
Dim rdr = sqlCmd.ExecuteReader
Dim rdr2 = sqlCmd2.ExecuteReader
While rdr.Read
theResults2.Add(New SocioInfo With {
.Nombre = rdr.GetString(0),
.LastName = rdr.GetString(1)
})
End While
While rdr2.Read
theResults2.Add(New SocioInfo With {
.CuentaName = rdr.GetString(0),
.AcctNum = rdr.GetValue(1),
.AcctFull = rdr2.GetValue(2),
.Balance = rdr2.GetValue(3)
})
End While
End Using
Return theResults2
End Function
I am not 100% sure if this is the best way to do this (basically need to get data from two different tables). Thing is, while Rdr shows me no error, Rdr2 just blows in the face. The exception is this:
Invalid attempt to read when no data is present.
In the second loop you are trying to use the first SqlDataReader but this is not possible because the first loop has already reached the end of the input data.
If you need joined data between the two tables a better approach is to use just one query using the JOIN operator. This query works assuming that each customer in the CustInfo table has one account in the ACCT_NEW table
Dim sql = "SELECT c.FirstName, c.LastName, a.AcctName, a.AcctNum, a.NewAcct, a.Balance " & _
"FROM CustInfo c INNER JOIN ACCT_NEW a ON a.AcctNum = c.NumCuenta " & _
"WHERE NumCuenta = #SocioNum "
Using conn = New SqlConnection(connStr)
Dim sqlCmd = New SqlCommand(sql, conn)
sqlCmd.Parameters.AddWithValue("#SocioNum", CDbl(txtInput.Text))
conn.Open()
Dim rdr = sqlCmd.ExecuteReader
While rdr.Read
theResults2.Add(New SocioInfo
With {
.Nombre = rdr.GetString(0),
.LastName = rdr.GetString(1)
.CuentaName = rdr.GetString(2),
.AcctNum = rdr.GetValue(3),
.AcctFull = rdr.GetValue(4),
.Balance = rdr.GetValue(5)
})
End While
End Using

Insert and Update with XML in stored procedure

I need some help in using a stored procedure in my case below: I have a table with a single XML column which takes in fields VoucherCode and Quantity, the data in SQL xml column looks like this:
<CampaignVoucher xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" VoucherCode="Vouch001" Quantity="2" />
The below method will call my stored procedure to check if a particular voucher exist based on my voucher code and then either add a new row or update an existing voucher in my gridview:
Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAdd.Click
Dim dbCommand As DbCommand = Nothing
'Dim cmd As New SqlCommand()
If TextBox1.Text = "" Or DropDownList1.SelectedIndex = 0 Then
Exit Sub
End If
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("Test").ConnectionString)
Dim da As New SqlDataAdapter("SELECT CustomerID, VoucherXML FROM Customers", con)
Dim cmd As New SqlCommand("Campaign_InsertRewardsVoucher_XML", con)
cmd.CommandType = CommandType.StoredProcedure
Dim dt As New DataTable()
da.Fill(dt)
' Here we'll add a blank row to the returned DataTable
Dim dr As DataRow = dt.NewRow()
dt.Rows.InsertAt(dr, 0)
'Creating the first row of GridView to be Editable
GridView1.EditIndex = 0
GridView1.DataSource = dt
GridView1.DataBind()
'Changing the Text for Inserting a New Record
DirectCast(GridView1.Rows(0).Cells(0).Controls(0), LinkButton).Text = "Insert"
' Serialization ----------------------------
Dim cm As New CampaignVoucher(DropDownList1.SelectedValue, TextBox1.Text)
Dim serializer As New XMLserializer(cm.[GetType]())
Dim memoryStream As New MemoryStream()
Dim writer As New XmlTextWriter(memoryStream, Encoding.UTF8)
serializer.Serialize(writer, cm)
'get the stream from the writer
memoryStream = TryCast(writer.BaseStream, MemoryStream)
'apply encoding to the stream
Dim enc As New UTF8Encoding()
Dim xml As String = enc.GetString(memoryStream.ToArray()).Trim()
' -------------------------------------------
cmd.Parameters.Add("#p1", SqlDbType.VarChar, 50).Value = DropDownList1.SelectedValue
cmd.Parameters.Add("#p2", SqlDbType.Text).Value = xml
cmd.Connection = con
con.Open()
cmd.ExecuteScalar()
con.Close()
GridView1.EditIndex = -1
BindData()
TextBox1.Text = ""
End Sub
Backtrack a little, I wrote this working stored proc as shown below for the same purpose just that it was meant for a conventional storage: 1 table with a VoucherCode and Quantity column, now with the XML column, now encapsulating both VoucherCode and Quantity values, I am lost to how to rewrite my stored proc, tried different ways but apparently I made a mess out of it, please advice, thanks!:
ALTER PROCEDURE [dbo].[Campaign_InsertRewardsVoucher]
#VoucherCode nvarchar(50) =NULL,
#Quantity int = NULL
--#ExistingQuantity int = NULL
AS
BEGIN
DECLARE #ExistingQuantity Int = Null
IF EXISTS (SELECT * FROM ForTest_Campaign_Voucher WHERE VoucherCode=#VoucherCode)
BEGIN
SET #ExistingQuantity = (SELECT Quantity from ForTest_Campaign_Voucher Where VoucherCode=#VoucherCode)
SET #ExistingQuantity = (#ExistingQuantity + #Quantity)
UPDATE ForTest_Campaign_Voucher SET VoucherCode=#VoucherCode, Quantity=#ExistingQuantity Where VoucherCode=#VoucherCode
END
ELSE
INSERT INTO ForTest_Campaign_Voucher(VoucherCode, Quantity) VALUES(#VoucherCode, #Quantity)
END
ALTER PROCEDURE [dbo].[Campaign_InsertRewardsVoucher]
#VoucherCode nvarchar(50) =NULL,
#Quantity int = NULL
AS
BEGIN
DECLARE #ExistingQuantity Int
SET #ExistingQuantity = (SELECT xmlFieldName.value('(/CampaignVoucher/#Quantity)[1]', 'int')
FROM ForTest_Campaign_Voucher
WHERE xmlFieldName.value('(/CampaignVoucher/#VoucherCode)[1]', 'nvarchar(50)') = #VoucherCode)
IF #ExistingQuantity IS NULL
BEGIN
INSERT INTO ForTest_Campaign_Voucher
(
xmlFieldName
)
VALUES
(
'<CampaignVoucher xmlns:xsd="http://www.w3.org/2001/XMLSchema" VoucherCode="' + #VoucherCode + '" Quantity="' + CAST(#Quantity AS NVARCHAR(16)) + '" />'
)
END
ELSE
DECLARE #NewQuantity INT
SET #NewQuantity = #ExistingQuantity + #Quantity
UPDATE ForTest_Campaign_Voucher
SET xmlFieldName='<CampaignVoucher xmlns:xsd="http://www.w3.org/2001/XMLSchema" VoucherCode="' + #VoucherCode + '" Quantity="' + CAST(#NewQuantity AS NVARCHAR(16)) + '" />'
WHERE xmlFieldName.value('(/CampaignVoucher/#VoucherCode)[1]', 'nvarchar(50)') = #VoucherCode
END
GO

Resources