I am trying to page through BigQuery data with vb.net. I keep getting the same first page of data with my code. The way I understand, I need to set the pagetoken of the response to look at the next page.
With the following code, I only get the first page of data while never exiting my loop.
For the login I was setting the Oauthtoken of my queryrequest and that was getting the first page fine, but no attempt is made to page through the results that way.
I appreciate any lead in the right direction.
Dim DT As New DataTable
Dim ErrMessage As String = ""
Try
Dim INIT As New BigqueryService.Initializer
Dim scopes As IList(Of String) = New List(Of String)()
scopes.Add(BigqueryService.Scope.Bigquery)
Dim credential As UserCredential
Using stream As New FileStream("client_secrets.json", FileMode.Open, FileAccess.Read)
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, scopes, "user", CancellationToken.None, New FileDataStore("BQ.App")).Result
End Using
INIT.HttpClientInitializer = credential
Dim service As New BigqueryService(INIT)
Dim j As JobsResource = service.Jobs
Dim req As New QueryRequest
req.Query = tQuery.Text
Dim QRequest As JobsResource.QueryRequest = j.Query(req, projectId)
QRequest.OauthToken = MyAccessToken
Dim JOBID As String = QRequest.Execute.JobReference.JobId
Dim DATA = QRequest.Execute
Dim schema = DATA.Schema
For Each col In schema.Fields
DT.Columns.Add(col.Name)
Next
Dim page_Tok = ""
Dim rr As GetQueryResultsResponse
While True
Try
rr.PageToken = page_Tok
Catch ex As Exception
'No Token Yet
End Try
rr = j.GetQueryResults(projectId, JOBID).Execute
page_Tok = rr.PageToken
If rr.JobComplete = True Then
If page_Tok = "" Then
Exit While
End If
End If
Dim resp2 = rr.Rows
For Each row In resp2
Dim DR As DataRow = DT.NewRow
For f = 0 To row.F.Count - 1
Dim field = row.F
DR(f) = row.F(f).V
Next
DT.Rows.Add(DR)
Next
End While
Catch ex As Exception
ErrMessage = ex.Message
End Try
I'm not a VB expert, but you're not setting the page token in the GetQueryResultsRequest, you're setting it in the response. See https://developers.google.com/resources/api-libraries/documentation/bigquery/v2/csharp/latest/classGoogle_1_1Apis_1_1Bigquery_1_1v2_1_1JobsResource_1_1GetQueryResultsRequest.html
I think that this will work:
req = j.GetQueryResults(projectId, JOBID)
req.PageToken = page_tok
rr = req.Execute
Related
I am manage to create spreadsheet on google drive using following code.
Now I want to add new sheets in that created spreadsheet.
When I Create new spreadsheet , it contains default sheet having name Sheet1 but I want to rename that sheet or insert more than one sheets in Spreadsheet
Public Function Create(ByVal FileName As String) As String
Try
Dim service = GetGoogleAPPDriveService()
Dim fileMetadata = New Google.Apis.Drive.v3.Data.File()
fileMetadata.Name = FileName
fileMetadata.MimeType = "application/vnd.google-apps.spreadsheet"
Dim request As FilesResource.CreateRequest = service.Files.Create(fileMetadata)
request.SupportsTeamDrives = True
request.Fields = "id"
System.Net.ServicePointManager.ServerCertificateValidationCallback = New System.Net.Security.RemoteCertificateValidationCallback(AddressOf AcceptAllcertification)
Dim file = request.Execute
Return file.Id
Catch ex As Exception
Throw ex
End Try
End Function
Private Function GetGoogleAPPDriveService() As DriveService
Try
Dim Scopes1 As String() = {DriveService.Scope.Drive, DriveService.Scope.DriveFile}
Dim ClientId As String = ""
Dim ClientSecret As String = ""
Dim UserCredentials As UserCredential
Dim stream = New FileStream("credentials.json", FileMode.Open, FileAccess.Read)
ClientId = GoogleClientSecrets.Load(stream).Secrets.ClientId
Dim stream1 = New FileStream("credentials.json", FileMode.Open, FileAccess.Read)
ClientSecret = GoogleClientSecrets.Load(stream1).Secrets.ClientSecret
Dim cs = New ClientSecrets()
cs.ClientId = ClientId
cs.ClientSecret = ClientSecret
UserCredentials = GoogleWebAuthorizationBroker.AuthorizeAsync(cs, Scopes1, Environment.UserName,
CancellationToken.None, New FileDataStore("MyAppsToken", True)).Result
Dim service = New DriveService(New BaseClientService.Initializer() With {
.HttpClientInitializer = UserCredentials,
.ApplicationName = ApplicationName})
Return service
Catch ex As Exception
Throw ex
End Try
End Function
Public Function AcceptAllcertification(ByVal sender As Object, ByVal Certification As X509Certificate, ByVal Chain As X509Chain, ByVal sslPolicyErrors As System.Net.Security.SslPolicyErrors) As Boolean
Return True
End Function
You need to use the Sheets API for that. Have a look at the AddSheetRequest
Its hard to identify which request has to be used in .net from json file .
I succeed to add sheet in existing Spread sheet . Here I am put vb.net code if any one needed
Public Function Addsheet(ByVal FileId As String, ByVal sheetName As String) As String
Try
Dim serv = GetGoogleAPPSheetService()
Dim updatesheet = New BatchUpdateSpreadsheetRequest
Dim Req_Request As Request = New Request
Dim Req_AddSheet As New AddSheetRequest
Dim prop As New SheetProperties
prop.Title = sheetName
Req_AddSheet.Properties = prop
Req_Request.AddSheet = Req_AddSheet
Dim IList_req As IList(Of Request)
Dim List_req1 = New List(Of Request)
List_req1.Add(Req_Request)
IList_req = List_req1.ToList
updatesheet.Requests = IList_req
Dim req = serv.Spreadsheets.BatchUpdate(updatesheet, FileId)
Dim response = req.Execute
Catch ex As Exception
Throw ex
End Try
End Function
Private Function GetGoogleAPPSheetService() As SheetsService
Try
Dim UserCredentials As UserCredential
Using stream = New FileStream("credentials.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = "token.json" 'System.Environment.GetFolderPath(Environment.SpecialFolder.Personal)
'credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json")
UserCredentials = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
End Using
Dim service = New SheetsService(New BaseClientService.Initializer() With {
.HttpClientInitializer = UserCredentials,
.ApplicationName = ApplicationName})
Return service
Catch ex As Exception
Throw ex
End Try
End Function
My application is a web scraper (for the most part) that stores information in a database. I have 2 classes so far:
clsSpyder - This essentially rolls-up the scraper processes
clsDB - This does any database processes
My test program looks over all the URLs, scrapes, pushes into the database. It is pretty simple sequentially, but I would like to have say N number of threads running those processes (scrape and store). My sequential code is this:
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
'Grab List
Dim tDS As New DataSet
Dim tDB As New clsTermsDB
Dim tSpyder As New clsAGDSpyder
Dim sResult As New TermsRuns
'Grab a list of all URLS
tDS = tDB.GetTermsList(1)
Try
For Each Row As DataRow In tDS.Tables(0).Rows
rtbList.AppendText(Row("url_toBeCollected") & vbCrLf)
sResult = tSpyder.SpiderPage(Row("url_toBeCollected"))
'If nothing is found, do not store
If sResult.html <> "" And sResult.text <> "" Then
tDB.InsertScrape(Now(), sResult.html, sResult.text, Row("url_uid"), 1)
End If
Next
Exit Sub
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
With that in mind and noting that I am passing variables to the SpiderPage and InsertScrape methods.. How could I implement threading? It's gotta be simple, but I feel like I have been googling and trying things for days without success :(
*** ADDED: SpiderPage method:
Public Function SpiderPage(PageURL As String) As TermsRuns
Dim webget As New HtmlWeb
Dim node As HtmlNode
Dim doc As New HtmlDocument
Dim docNOHTML As HtmlDocument
Dim uri As New Uri(PageURL)
Dim wc As HttpWebRequest = DirectCast(WebRequest.Create(uri.AbsoluteUri), HttpWebRequest)
Dim wcStream As Stream
wc.AllowAutoRedirect = True
wc.MaximumAutomaticRedirections = 3
'Set Headers
wc.UserAgent = "Mozilla/5.0 (Macintosh; I; Intel Mac OS X 11_7_9; de-LI; rv:1.9b4) Gecko/2012010317 Firefox/10.0a4"
wc.Headers.Add("REMOTE_ADDR", "66.83.101.5")
wc.Headers.Add("HTTP_REFERER", "66.83.101.5")
'Set HTMLAgility Kit Useragent Spoofing (not needed, I don't think)
webget.UserAgent = "Mozilla/5.0 (Macintosh; I; Intel Mac OS X 11_7_9; de-LI; rv:1.9b4) Gecko/2012010317 Firefox/10.0a4"
'Certification STuff
wc.UseDefaultCredentials = True
wc.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials
ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications
'Create Cookie Jar
Dim CookieJar As New CookieContainer
wc.CookieContainer = CookieJar
'Keep Alive Settings
wc.KeepAlive = True
wc.Timeout = &H7530
'Read the web page
Dim wr As HttpWebResponse = Nothing
Try
wcStream = wc.GetResponse.GetResponseStream
doc.Load(wcStream)
'Remove HTML from the document
docNOHTML = RemoveUnWantedTags(doc)
'Grab only the content inside the <body> tag
node = docNOHTML.DocumentNode.SelectSingleNode("//body")
'Output
SpiderPage = New TermsRuns
SpiderPage.html = node.InnerHtml
SpiderPage.text = node.InnerText
Return SpiderPage
Catch ex As Exception
'Something goes here when scraping returns an error
SpiderPage = New TermsRuns
SpiderPage.html = ""
SpiderPage.text = ""
End Try
End Function
*** Added InsertScrape:
Public Function InsertScrape(scrape_ts As DateTime, scrape_html As String, scrape_text As String, url_id As Integer, tas_id As Integer) As Boolean
Dim myCommand As MySqlClient.MySqlCommand
Dim dt As New DataTable
'Create ds/dt for fill
Dim ds As New DataSet
Dim dtbl As New DataTable
Try
'Set Connection String
myConn.ConnectionString = myConnectionString
'Push Command to Client Object
myCommand = New MySqlClient.MySqlCommand
myCommand.Connection = myConn
myCommand.CommandText = "spInsertScrape"
myCommand.CommandType = CommandType.StoredProcedure
myCommand.Parameters.AddWithValue("#scrape_ts", scrape_ts)
myCommand.Parameters("#scrape_ts").Direction = ParameterDirection.Input
myCommand.Parameters.AddWithValue("#scrape_html", scrape_html)
myCommand.Parameters("#scrape_html").Direction = ParameterDirection.Input
myCommand.Parameters.AddWithValue("#scrape_text", scrape_text)
myCommand.Parameters("#scrape_text").Direction = ParameterDirection.Input
myCommand.Parameters.AddWithValue("#url_id", url_id)
myCommand.Parameters("#url_id").Direction = ParameterDirection.Input
myCommand.Parameters.AddWithValue("#tas_id", tas_id)
myCommand.Parameters("#tas_id").Direction = ParameterDirection.Input
'Open Connection
myConn.Open()
myCommand.ExecuteNonQuery()
'Close Connection
myConn.Close()
InsertScrape = True
Catch ex As Exception
'Put Message Here
InsertScrape = False
MessageBox.Show(ex.Message)
End Try
End Function
thanks in advance.
I try to obtain a certificate with LDAP, but i have an exception
System.Runtime.InteropServices.COMException(0x80072030): There is no such object on the server at System
My code :
Dim ldapUrl = "LDAP://annuaire.sesam-vitale.fr/cn=amo_pj.test#test.rss.fr,ou=AC-FACTURATION,ou=AC-SESAM-VITALE-2034,o=sesam-vitale,c=fr?userCertificate;binary"
Dim de As DirectoryEntry = New DirectoryEntry(ldapUrl)
de.AuthenticationType = AuthenticationTypes.None
Dim dsearch As DirectorySearcher = New DirectorySearcher(de)
dsearch.Filter = "(objectClass=*)"
Dim rs As SearchResult = dsearch.FindOne()
I have this exception at last line. I have no idea and need your help.
Thank you
(sorry for my english)
EDIT
I resolve my problem :
Public Function certificatLDAP() As X509Certificate2
Dim certificat As X509Certificate2 = Nothing
Dim ldapconn As LdapConnection = New LdapConnection(New LdapDirectoryIdentifier("annuaire.sesam-vitale.fr"))
Try
ldapconn.AuthType = AuthType.Anonymous
ldapconn.SessionOptions.ProtocolVersion = 3
Dim attribut(1) As String
attribut(0) = "userCertificate;binary"
Dim request As SearchRequest = New SearchRequest("cn=amo_pj.test#test.rss.fr,ou=AC-FACTURATION,ou=AC-SESAM-VITALE-2034,o=sesam-vitale,c=fr", "(ObjectClass=*)", Protocols.SearchScope.Base, attribut)
Dim reponse As SearchResponse = CType(ldapconn.SendRequest(request), SearchResponse)
For Each test As SearchResultEntry In reponse.Entries
For Each toto As DictionaryEntry In test.Attributes
Dim tata As DirectoryAttribute = toto.Value
Dim tutu As Byte() = tata(0)
Return New X509Certificate2(tutu)
Next
Next
Catch ex As Exception
Throw ex
Finally
ldapconn.Dispose()
End Try
Return certificat
End Function
am trying to use the DocuSign .Net Client to request a signature on a Document I am creating dynamically. So far, I have been able to change the example to vb.net and it works (Exmaple CS). I was converting the "Walkthrough #4 - Request Signature on Document", about 1/2 way down the code. Now I am trying to use the Envelope.Document I've seen in other examples, such as, DocuSign example. But it seems .Document is not part of Envelope, even thought the rest of the code in both examples translates to vb.
My other option is to use the Envelope.AddDocument but I can't seem to figure out what it's expecting. I am supposed to pass fileBytes() as Byte, fileName as String, and index As Integer. I've tried a couple different methods to get the fileBytes but keep getting an error about Invalid_Content_Type Content type is not supported.
Here is the code I've been trying. Any help on how to add a Document to an Envelope would be appreciated. Ultimately I want to be able to add multiple documents to the one envelope. I can get the env.Create(docPath) to work, but that is not helpful.
Thank you in advance for any help you can offer.
Public Function RequestEsignature(email As String, rName As String, docPath As String, strSubject As String) As String
main()
Dim AccountEmail = My.Settings.docusignUserName
Dim AccountPassword = My.Settings.docusignPassword
Dim RecipientEmail = email
Dim RecipientName = rName
Dim documentPath = docPath
Dim msgString As String
Dim acct As Account = New Account()
acct.Email = AccountEmail
acct.Password = AccountPassword
Dim result As Boolean = acct.Login()
If Not result Then
msgString = String.Format("There was an error logging in to DocuSign fo user {0}.\nError Code: {1}\nMessage: {2}", acct.Email, acct.RestError.errorCode, acct.RestError.message)
MsgBox(msgString)
Return Nothing
End If
Dim env As Envelope = New Envelope
env.Login = acct
env.Recipients = New Recipients()
Dim signer(0) As Signer
signer(0) = New Signer()
signer(0).email = email
signer(0).name = RecipientName
signer(0).routingOrder = "1"
signer(0).recipientId = "1"
env.Recipients.signers = signer
Dim envDocs = New Document()
envDocs.documentId = "1"
envDocs.name = "Test Document"
envDocs.uri = docPath
'Dim fileBytes As Byte()
'Dim fileBytes = getByteArrayII(documentPath)
'Dim oFile As FileInfo
'oFile = New FileInfo(documentPath)
'Dim oFileStream As FileStream = oFile.OpenRead()
'Dim lBytes As Long = oFileStream.Length
'If lBytes > 0 Then
' Dim fileData(lBytes - 1) As Byte
' oFileStream.Read(fileData, 0, lBytes)
'If Not env.AddDocument(fileBytes, documentPath, 0) Then
' msgString = String.Format("The was an Error adding the Document." & vbCrLf & "Error Code: {0} " & vbCrLf & "Message: {1}", env.RestError.errorCode, env.RestError.message)
' MsgBox(msgString)
' Return Nothing
'Else
' MsgBox("Doc Successfully Added")
'End If
'oFileStream.Close()
'End If
env.Status = "sent"
env.EmailSubject = strSubject
result = env.Create()
If Not result Then
If Not IsNothing(env.RestError) Then
msgString = String.Format("Error Code: {0}\nMessage: {1}", env.RestError.errorCode, env.RestError.message)
MsgBox(msgString)
Return Nothing
Else
MsgBox("There was a nondescript error while processing this request. \nPLease verify all information is correct before trying again.")
Return Nothing
End If
Else
Return env.EnvelopeId
End If
End Function
Private Function getByteArray(fileName As String) As Byte()
Dim fInfo As New FileInfo(fileName)
Dim numBytes As Long = fInfo.Length
Dim fStream As New FileStream(fileName, FileMode.Open, FileAccess.Read)
Dim br As New BinaryReader(fStream)
Dim data As Byte() = br.ReadBytes(CInt(numBytes))
br.Close()
fStream.Close()
Return data
End Function
Private Function getByteArrayII(ByVal fileName As String) As Byte()
Dim tempByte() As Byte = Nothing
If String.IsNullOrEmpty(fileName) Then
Throw New ArgumentNullException("FileName Not Provided")
Return Nothing
End If
Try
Dim fileInfo As New FileInfo(fileName)
Dim numBytes As Long = fileInfo.Length
Dim fStream As New FileStream(fileName, FileMode.Open, FileAccess.Read)
Dim binaryReader As New BinaryReader(fStream)
tempByte = binaryReader.ReadBytes(Convert.ToInt32(numBytes))
fileInfo = Nothing
numBytes = 0
fStream.Close()
fStream.Dispose()
Return tempByte
Catch ex As Exception
Return Nothing
End Try
End Function
HISTORY
I am new to vb.net and programming. Thus far I have been able to make a program that allows users to enter client information with the forms being changed based on certain selections. We have a system that uses our SQL data to do mail merges in Word and then send a PDF for esignature to the client through DocuSign. We are using a SQL backend and a vb.net front end.
Lastly, I have been looking for an answer over the weekend and am now reaching out for help. I have searched google for every possible term(s) I can think to include/exclude. If I am asking publicly that truly means I have exhausted every resource I have. Please do not post links to any DocuSign Documentation as I have already visited all those sites. Thank you.
It doesn't appear that the Envelope class has a Document property, but rather a Documents property which seems to be an array.
The C# example you posted at this link seems to show how to attach a document:
// Attach the document(s) C#
envelope.Documents = new DocuSignWeb.Document[1];
DocuSignWeb.Document doc = new DocuSignWeb.Document();
doc.ID = "1";
doc.Name = "Document Name";
doc.PDFBytes = [Location of Document];
envelope.Documents[0] = doc;
Which in VB would be something like this:
'Attach the document(s) VB
envelope.Documents = new DocuSignWeb.Document(0);
Dim doc As New DocuSignWeb.Document()
doc.ID = "1"
doc.Name = "Document Name"
doc.PDFBytes = [Location of Document]
envelope.Documents(0) = doc
If this is not the problem you are facing, please provide additional details.
Clearly my approach to learning vb, api's and all the other stuff needed to get my program working is extremely daunting. I am not sure if it is my lack of knowledge or just a misunderstanding of the code, but I was finally able to get this figured out.
My function takes an object 'client' that has things like Name and Email, I also pass a list of Document Paths and the Subject line for the email. This loops through the list of documents and adds them to the envelope. I also have some examples of adding Tags which was a learning process in itself. I hope I am the only one unfortunate enough to have to be learning so many different new concepts that something this simple takes months to figure out, but if not here's the code:
'Request Signature - Send Envelope
Public Function RequestEsignature(pClient As iqClient, docPaths As List(Of String), strSubject As String) As DocuSign.Integrations.Client.Envelope
'*****************************************************************
' ENTER VALUES FOR FOLLOWING VARIABLES!
'*****************************************************************
Dim AccountEmail As String = My.Settings.docusignUserName
Dim AccountPassword As String = My.Settings.docusignPassword
Dim RecipientEmail As String = pClient.Email
Dim RecipientName As String = pClient.Name.NameFL
'*****************************************************************
' user credentials
Dim account As New Account()
account = LoginToDocusign()
If Not IsNothing(account) Then
End If
Dim result As Boolean ' = account.Login()
' create envelope object and assign login info
Dim envelope As New Envelope()
Dim recip = New Recipients()
Dim signers = New List(Of Signer)
Dim signer As New Signer()
signer.email = RecipientEmail
signer.name = RecipientName
signer.routingOrder = "1"
signer.recipientId = "1"
Dim fileBytes = New List(Of Byte())
Dim docNames = New List(Of String)
Dim iqDoc As iqPublicClasses.iqDocement
Dim docs = New List(Of Document)
Dim doc As Document
Dim tabs = New List(Of Tab)
Dim tab As New Tab()
Dim iTabs = New List(Of Tab)
Dim iTab As New Tab()
Dim dTabs = New List(Of DateSignedTab)
Dim dTab As New DateSignedTab
Dim rTabs = New List(Of RadioGroupTab)
Dim rTab As New RadioGroupTab()
Dim radios = New List(Of Radios)
Dim radio As New Radios()
tab = New Tab()
tab.anchorIgnoreIfNotPresent = True
tab.anchorString = "\s1\"
tabs.Add(tab)
dTab = New DateSignedTab
dTab.anchorIgnoreIfNotPresent = True
dTab.anchorString = "\d1\"
dTabs.Add(dTab)
iTab = New Tab()
iTab.anchorIgnoreIfNotPresent = True
iTab.anchorString = "\i1\"
iTab.anchorYOffset = 15
iTabs.Add(iTab)
iTab = New Tab()
iTab.anchorIgnoreIfNotPresent = True
iTab.anchorString = "\nri1\"
iTabs.Add(iTab)
rTab = New RadioGroupTab()
rTab.groupName = "RG1"
rTab.anchorIgnoreIfNotPresent = True
radio = New Radios()
radio.anchorString = "\rbn\"
radio.anchorIgnoreIfNotPresent = True
radio.anchorYOffset = -10
radios.Add(radio)
radio = New Radios()
radio.anchorString = "\rby\"
radio.anchorIgnoreIfNotPresent = True
radio.anchorYOffset = -10
radios.Add(radio)
rTab.radios = radios.ToArray
rTabs.Add(rTab)
signer.tabs = New Tabs()
signer.tabs.signHereTabs = tabs.ToArray
signer.tabs.dateSignedTabs = dTabs.ToArray
signer.tabs.initialHereTabs = iTabs.ToArray
signer.tabs.radioGroupTabs = rTabs.ToArray
Dim cnt = 0
For Each docName As String In docPaths
cnt += 1
iqDoc = New iqPublicClasses.iqDocement(docName)
doc = New Document()
doc.attachmentDescription = iqDoc.Name
doc.name = String.Format("{0}{1}", iqDoc.Name, iqDoc.Extension)
doc.fileExtension = iqDoc.Extension
doc.uri = iqDoc.FullPath
doc.documentId = cnt
docs.Add(doc)
docNames.Add(iqDoc.FullPath)
fileBytes.Add(File.ReadAllBytes(iqDoc.FullPath))
Next
' create envelope and send the signature request (since status is set to "sent")
envelope.Login = account
signers.Add(signer)
recip.signers = signers.ToArray
envelope.Recipients = recip
envelope.Status = "sent"
envelope.EmailSubject = strSubject
result = envelope.Create(fileBytes, docs)
If Not result Then
If envelope.RestError IsNot Nothing Then
Console.WriteLine("Error code: {0}" & vbLf & "Message: {1}", envelope.RestError.errorCode, envelope.RestError.message)
Return Nothing
Else
Console.WriteLine("Error encountered while requesting signature from template, please review your envelope and recipient data.")
Return Nothing
End If
Else
Console.WriteLine("Signature request has been sent to {0}, envelopeId is {1}.", envelope.Recipients.signers(0).email, envelope.EnvelopeId)
Return envelope
End If
End Function
PS - As I've said I am extremely new to this and am learning as I am going. I understand this may not be the most elegant approach or properly formatted code, but I unfortunately have very little time to go back an update code I've written. Hopefully one day I will be able to go back and fix all the stuff I didn't understand when I first created it.
I have a function which gets json string from jsonblob, deserializers it and returns in dataview. I want to know how can i insert the data from the dataview into my sql database using vb.net
My function is as follows
Public Function GetJsonString() As DataView
Dim dsContactMeta As DataSet = Nothing
Dim dv As DataView = Nothing
'url declaration for REST_ContactMeta
Dim REST_ContactMetaURL As Uri = New Uri("http://jsonblob.com/api/jsonBlob/5420df11e4b00ad1f05ed29b")
Dim strJSONData As String = ""
Dim response As HttpWebResponse
Dim reader As StreamReader
Try
Dim httpWebRequest As HttpWebRequest = WebRequest.Create(REST_ContactMetaURL)
httpWebRequest.Method = WebRequestMethods.Http.Get
httpWebRequest.ContentType = "application/json"
response = httpWebRequest.GetResponse()
reader = New StreamReader(response.GetResponseStream)
strJSONData = reader.ReadToEnd
strJSONData = "[" & strJSONData & "]" 'had to wrap the raw JSON data with brackets for parsing purposes
Dim myXmlNode As System.Xml.XmlNode = JsonConvert.DeserializeXmlNode("{""root"":" + strJSONData + "}", "root") 'error is thrown if the JSON does not have a root element
' Dim myXmlNode As System.Xml.XmlNode = JsonConvert.DeserializeXmlNode(strJSONData)
dsContactMeta = New DataSet("Test")
Try
dsContactMeta.ReadXml(New XmlNodeReader(myXmlNode))
If dsContactMeta.Tables("root") Is Nothing Or dsContactMeta.Tables("root").Rows.Count = 0 Then
Return Nothing 'in case of error return nothing
Else
dsContactMeta.Tables("root").Columns("job_id").SetOrdinal(0) 'setting the field name as the first column
dv = New DataView
dv.Table = dsContactMeta.Tables("root")
Return dv
End If
Catch ex As Exception
Return Nothing
End Try
Catch ex As Exception
Return Nothing 'if for any reason the API has failed connecting to the server or other unknown error then return nothing
End Try
End Function
Insert record into database from DataView, for that you need to read DataView:
For Each rowView As DataRowView In dataView
Debug.Write(item & " ")
Dim row as DataRow = rowView.Row;
// Do something //
//insert into tablename(col1,col2,..) values(row['col1'],row['col2'],..)
Next