Reading xmlNodeList into a Dataset using VB.NET - asp.net

UPDATE:
I want to dynamically dump the XML returned into a dataset without having to write out the columns names. The data returned is in very simple format, name of column, the data, then close of the name of column. Like this:
<runsql>
<cst_id>0005675667</cst_id>
<ind_last_name>Abe</ind_last_name>
<ind_first_name>Adam</ind_first_name>
<cst_ixo_title_dn/>
<cst_org_name_dn>Acme University</cst_org_name_dn>
<cst_eml_address_dn>Adam#acmeu.edu</cst_eml_address_dn>
</runsql>
I've been using a standard format to access our web services and return specific fields. I'm needing to modify this to dump the whole XML feed into an internal Dataset in VB.NET. This web service is pre-defined in my Web References section. I am successful with below code, but can't figure out a way, after much Googling and testing, to dynamically load all the columns into a Dataset. Can I get help using this format below to load into a Dataset?
Dim proxy As New myWS.netFORUMXMLWebServices
Dim strInSQL As String
Dim strOutXML2 As XmlDocument
strOutXML2 = New XmlDocument
Dim oNode2 As XmlNode
Dim oResultsNode2 As XmlNode
strInSQL = "SELECT cst_eml_address_dn FROM WebServicesTable"
strOutXML2.LoadXml("<myResults></myResults>")
oResultsNode2 = proxy.runsql(strInSQL)
Dim xmlNewDoc As XmlDocument
xmlNewDoc = New XmlDocument
xmlNewDoc.LoadXml(oResultsNode2.OuterXml)
strOutXML2.DocumentElement.AppendChild(strOutXML2.ImportNode(xmlNewDoc.DocumentElement, True))
Dim oResultsNodeList2 As XmlNodeList
oResultsNodeList2 = xmlNewDoc.SelectNodes("//runsql")
For Each oNode2 In oResultsNodeList2
returnedEmail = oNode2.SelectSingleNode("cst_eml_address_dn").InnerText
Next
And in case you were wondering the "runsql" is the parameter at the end of our web services that our vendor gave us. (webservices.asmx?op=runsql)

Basically, you just need to load the XMLDocument using DataSet.ReadXML. Here is one way:
' build xmlDoc to stand in for [proxy.runsql] return
Dim xdoc As New XmlDocument
' xml literal for the data
Dim x = <Document>
<Employee>
<Name>Ziggy Foobar</Name>
<HireDate>2/11/2010</HireDate>
</Employee>
<Elements>
<Name>Helium</Name>
<Symbol>He</Symbol>
</Elements>
<Employee>
<Name>Zoey Foobaz</Name>
<HireDate>2/11/2013</HireDate>
</Employee>
<runsql>
<cst_id>0005675667</cst_id>
<ind_last_name>Abe</ind_last_name>
<ind_first_name>Adam</ind_first_name>
<cst_ixo_title_dn/>
<cst_org_name_dn>Acme University</cst_org_name_dn>
<cst_eml_address_dn>Adam#acmeu.edu</cst_eml_address_dn>
</runsql>
</Document>
' load litersl to XmlDocument
xdoc.LoadXml(x.ToString)
'***** xdoc is now a stand in for the return from [proxy.runsql]
Dim ds As New DataSet
' load xdoc to dataset via node reader
Using xnr As New XmlNodeReader(xdoc)
ds.ReadXml(xnr) ' this is what you want
End Using ' dispose of node reader
Dim n As Integer ' test/view DS result
' verify: 2 tables?
For Each t As DataTable In ds.Tables
Console.WriteLine("Table: " & t.TableName)
' we know there are 2, just verifying
Console.WriteLine("Column Names: {0}, {1}", t.Columns(0).ColumnName,
t.Columns(1).ColumnName)
n = 1
For Each r As DataRow In t.Rows
' demo there only 2 cols
Console.WriteLine("[Item {0}]: {1}, {2}", n.ToString,
r(0).ToString, r(1).ToString)
n += 1
Next
Console.WriteLine()
Next
The end result is 3 tables in the DS, with the noncontiguous Employee data glued back together. There is no need to specify table or column names, it parses them itself. In your case, you could ignore any other tables in the DataSet other than "runsql". I pasted your runsql block after the test code was written, so some of the "only 2 columns" comments are wrong. Output:
Table: Employee
Column Names: Name, HireDate
[Item 1]: Ziggy Foobar, 2/11/2010
[Item 2]: Zoey Foobaz, 2/11/2013
Table: Elements
Column Names: Name, Symbol
[Item 1]: Helium, He
Table: runsql
Column Names: cst_id, ind_last_name
[Item 1]: 0005675667, Abe
Works on My MachineTM

Related

Open XML SDK Open and Save not working

I am having trouble with the Open XML SDK opening and saving word documents.
I am using the following code (VB.Net):
Try
'Set Path
Dim openPath As String = "../Documents/" & worddoc
Dim savePath As String = "\\web-dev-1\HR_Documents\" & worddoc
Using doc As WordprocessingDocument = WordprocessingDocument.Open("/Documents/" & worddoc, True)
'Employee Name Insert
'Find first table in document
Dim tbl1 As Table = doc.MainDocumentPart.Document.Body.Elements(Of Table).First()
'First Row in tbl
Dim row As TableRow = tbl1.Elements(Of TableRow)().ElementAt(0)
'Find first cell in row
Dim cell As TableCell = row.Elements(Of TableCell)().ElementAt(0)
'Insert selected Employee Name
Dim p As Paragraph = cell.Elements(Of Paragraph)().First()
Dim r As Run = p.Elements(Of Run)().First()
Dim txt As Text = r.Elements(Of Text)().First()
txt.Text = ddlEmployeeList.SelectedItem.Text
'Save File
'Supervisor Name Insert
'Find second table in document
Dim tbl2 As Table = doc.MainDocumentPart.Document.Body.Elements(Of Table).First()
'First Row in tbl
Dim row2 As TableRow = tbl2.Elements(Of TableRow)().ElementAt(0)
'Find first cell in row
Dim cell2 As TableCell = row2.Elements(Of TableCell)().ElementAt(0)
'Insert selected Employee Name
Dim p2 As Paragraph = cell2.Elements(Of Paragraph)().First()
Dim r2 As Run = p2.Elements(Of Run)().First()
Dim txt2 As Text = r2.Elements(Of Text)().First()
txt2.Text = ddlSupervisorList.SelectedItem.Text
End Using
Return 1
Catch ex As Exception
Return Nothing
End Try
The trouble starts on the first using statement. It throws the following error:
Could not find a part of the path 'C:\Documents\Hourly_Employee_Performance_Review .docx
I have placed the word documents in a folder of the ASP.NET site called Documents. I also have created a public share on the dev server to see if maybe that would help.
The problem is that it doesn't use the supplied path variable. I have gone through the documentation for OPEN XMl SDK but all it talks about is the Using Statement and its need and use for it.
Can anyone tell me, show me, or point to a site that has examples of how to set both the open path and save path?
You need a path to the file which is based on the filesytem, not a URL. You can do that with
Dim openPath As String = Path.Combine(Server.MapPath("~/Documents"), worddoc)
And then to open the file:
Using doc As WordprocessingDocument = WordprocessingDocument.Open(openPath, True)
It appears that you will need to do the same for the location to save to, but you didn't say if "\\web-dev-1" is a different server; if it were that would need other considerations.
(Not tested, some typos may exist. You will need an Imports System.IO.)

Converting string to XML node in VB.NET

I've an XML string in database column like this
<trueFalseQuestion id="585" status="correct" maxPoints="10"
maxAttempts="1"
awardedPoints="10"
usedAttempts="1"
xmlns="http://www.ispringsolutions.com/ispring/quizbuilder/quizresults">
<direction>You have NO control over how you treat customers.</direction>
<answers correctAnswerIndex="1" userAnswerIndex="1">
<answer>True</answer>
<answer>False</answer>
</answers>
</trueFalseQuestion>
But I need to do XML operations on this string like select its name, attributes values,inner text etc. How can I make this possible from this string
EDIT
Im sharing the code snippet I tried, but not working
Dim myXML As String
Dim gDt As New DataTable
gDt.Columns.Add("id")
gDt.Columns.Add("questionid")
gDt.Columns.Add("serial")
gDt.Columns.Add("direction")
Dim dr As DataRow
myXML ='<my above shared XML>'
Dim xmlDoc As New XmlDocument
xmlDoc.LoadXml(myXML)
dr = gDt.NewRow
dr("serial") = 1
dr("id") = xmlDoc.Attributes("id").Value
dr("direction") = xmlDoc("direction").InnerText
gDt.Rows.Add(dr)
But thats not working at all as I wish
There are many ways to parse XML in .NET, such as using one of the serialization classes or the XmlReader class, but the two most popular options would be to parse it with either XElement or XmlDocument. For instance:
Dim input As String = "<trueFalseQuestion id=""585"" status=""correct"" maxPoints=""10"" maxAttempts=""1"" awardedPoints=""10"" usedAttempts=""1"" xmlns=""http://www.ispringsolutions.com/ispring/quizbuilder/quizresults""><direction>You have NO control over how you treat customers.</direction><answers correctAnswerIndex=""1"" userAnswerIndex=""1""><answer>True</answer><answer>False</answer></answers></trueFalseQuestion>"
Dim element As XElement = XElement.Parse(input)
Dim id As String = element.#id
Or:
Dim input As String = "<trueFalseQuestion id=""585"" status=""correct"" maxPoints=""10"" maxAttempts=""1"" awardedPoints=""10"" usedAttempts=""1"" xmlns=""http://www.ispringsolutions.com/ispring/quizbuilder/quizresults""><direction>You have NO control over how you treat customers.</direction><answers correctAnswerIndex=""1"" userAnswerIndex=""1""><answer>True</answer><answer>False</answer></answers></trueFalseQuestion>"
Dim doc As New XmlDocument()
doc.LoadXml(input)
Dim nsmgr As New XmlNamespaceManager(doc.NameTable)
nsmgr.AddNamespace("q", "http://www.ispringsolutions.com/ispring/quizbuilder/quizresults")
Dim id As String = doc.SelectSingleNode("/q:trueFalseQuestion/#id", nsmgr).InnerText
Based on your updated question, it looks like the trouble you were having is that you weren't properly specifying the namespace. If you use XElement, it's much more forgiving (i.e. loose), but when you use XPath to select nodes in an XmlDocument, you need to specify every namespace, even when it's the default namespace on the top-level element of the document.

Can't insert row in google spreadsheets api with vb.net

could please anybody tell me what's wrong with my vb.net code?
Dim service As New SpreadsheetsService("MySpreadsheetIntegration-v1")
' TODO: Authorize the service object for a specific user (see other sections)
service.setUserCredentials("xxx#gmail.com", "1234")
' Instantiate a SpreadsheetQuery object to retrieve spreadsheets.
' Instantiate a SpreadsheetQuery object to retrieve spreadsheets.
Dim query As New SpreadsheetQuery()
' Make a request to the API and get all spreadsheets.
Dim feed As SpreadsheetFeed = service.Query(query)
' TODO: There were no spreadsheets, act accordingly.
If feed.Entries.Count = 0 Then
End If
' TODO: Choose a spreadsheet more intelligently based on your
' app's needs.
Dim spreadsheet As SpreadsheetEntry = DirectCast(feed.Entries(0), SpreadsheetEntry)
Console.WriteLine(spreadsheet.Title.Text)
' Get the first worksheet of the first spreadsheet.
' TODO: Choose a worksheet more intelligently based on your
' app's needs.
Dim wsFeed As WorksheetFeed = spreadsheet.Worksheets
Dim worksheet As WorksheetEntry = DirectCast(wsFeed.Entries(0), WorksheetEntry)
' Define the URL to request the list feed of the worksheet.
Dim listFeedLink As AtomLink = worksheet.Links.FindService(GDataSpreadsheetsNameTable.ListRel, Nothing)
' Fetch the list feed of the worksheet.
Dim listQuery As New ListQuery(listFeedLink.HRef.ToString())
Dim listFeed As ListFeed = service.Query(listQuery)
' Create a local representation of the new row.
Dim row As New ListEntry()
row.Elements.Add(New ListEntry.Custom() With { _
Key .LocalName = "ldVorname", _
Key .Value = "Joe" _
})
' Send the new row to the API for insertion.
service.Insert(listFeed, row)
Your code looks correct. Make sure you have added both Imports.
Imports Google.GData.Client
Imports Google.GData.Spreadsheets
I suspect you did an automatic c# to vb.net conversion. Remove the Key syntax in your code like this:
' Create a local representation of the new row.
Dim row As New ListEntry()
row.Elements.Add(New ListEntry.Custom() With { _
.LocalName = "ldVorname", _
.Value = "Joe" _
})
However, running this code stil gives a GDataRequestException saying We're sorry, a server error occurred. Please wait a bit and try reloading your spreadsheet.

webform multi column single row SQL Server result to vb variables

Ive looked through a few questions on here today and think I'm going round in circles.
My webform has a number of elements including username which is a drop down list (populated by a SQL statement)
On submit of the form i would like the code behind aspx.vb file run a select top 1 query and return a single row of data with 4 columns.
The returned SQL query result 4 columns would only be used later in the aspx.vb file so i want to assign each of the columns to a variable. I'm struggling with this task and assigning the variable the column result from the query.
Protected Sub submitbtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitbtn.Click
Dim connString1 As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ToString
Dim conn As New SqlConnection(connString1)
Dim sql1 As String = ""
Dim col1h As String = ""
Dim col2r As String = ""
Dim col3title As String = ""
Dim col4UQN As String = ""
sql1 = "SELECT TOP 1 col1h,col2r,col3title, col4UNQ from tblDistinctUserOHR where colID_Username= '" + username + "' "
Dim cmd1 As New SqlCommand(sql1, conn)
'open the connection
'run the sql
'the result will always be found but in case its not some form of safety catch (the variables stay as empty strings
'assign the results to the variables
'close connections
'lots of other code
End Sub
could someone point me in the right direction to run the SQL and assign the result to the the variables. I've been reading about ExecuteScalar() and SqlDataReader but that doesn't seem to be the correct option as the only examples I've found handle a single result or lots of rows with a single column
Thanks for any samples and pointers.
Try this:
Dim da As New OleDb.OleDbDataAdapter(sql1, conn)
Dim dt As New DataTable
da.Fill(dt)
If dt.Rows.Count < 0 Then
col1h = dt.Rows(0).Item("col1h")
col2r = dt.Rows(0).Item("col2r")
col3title = dt.Rows(0).Item("col3title")
col4UQN = dt.Rows(0).Item("col4UQN")
Else
'No rows found
End If

Importing a spreadsheet, but having trouble

I have a form that allows a user to import a spreadsheet. This spreadsheet is generally static when it comes to column headers, but now the users want to be able to include an optional column (called Notes). My code crashes when I try to read the column from the spreadsheet if it doesn't exist.
Dim objCommand As New OleDbCommand()
objCommand = ExcelConnection() 'function that opens spreadsheet and returns objCommand
Dim reader As OleDbDataReader
reader = objCommand.ExecuteReader()
While reader.Read()
Dim Employee As String = Convert.ToString(reader("User"))
Dim SerialNUM As String = Convert.ToString(reader("serialno"))
**Dim Notes As String = Convert.ToString(reader("notes"))**
If the spreadsheet contains a Notes column, all goes well. If not, crash. How can I check to see if the Notes column exists in the spreadsheet to avoid the crash?
Change the code to something like this:
[EDIT - changed code logic)
Dim fieldCount = reader.FieldCount
For i = 0 To fieldCount - 1
Dim colName = reader.GetName(i)
If (colName = "notes") Then
Dim Notes As String = reader.GetString(i)
End If
Next i
Perhaps OleDbDataReader.FieldCount could help you program a workaround.

Resources