Related
I have a json like with this format
[{"ts_id": "96643010","rows": "64","columns":"Timestamp,Value", "data": [["2021-09-01T11:00:00.000+07:00",206.95],["2021-09-01T12:00:00.000+07:00",206.96],["2021-09-01T13:00:00.000+07:00",206.97],["2021-09-01T14:00:00.000+07:00",206.95],["2021-09-01T15:00:00.000+07:00",206.92],["2021-09-01T16:00:00.000+07:00",206.89],["2021-09-01T17:00:00.000+07:00",206.86],["2021-09-01T18:00:00.000+07:00",206.83],["2021-09-01T19:00:00.000+07:00",206.80],["2021-09-01T20:00:00.000+07:00",206.77],["2021-09-01T21:00:00.000+07:00",206.74],["2021-09-01T22:00:00.000+07:00",206.71],["2021-09-01T23:00:00.000+07:00",206.68],["2021-09-02T00:00:00.000+07:00",206.65],["2021-09-02T01:00:00.000+07:00",206.63],["2021-09-02T02:00:00.000+07:00",206.65],["2021-09-02T03:00:00.000+07:00",206.67],["2021-09-02T04:00:00.000+07:00",206.69],["2021-09-02T05:00:00.000+07:00",206.71],["2021-09-02T06:00:00.000+07:00",206.73],["2021-09-02T07:00:00.000+07:00",206.75],["2021-09-02T08:00:00.000+07:00",206.76],["2021-09-02T09:00:00.000+07:00",206.77],["2021-09-02T10:00:00.000+07:00",206.78],["2021-09-02T11:00:00.000+07:00",206.79],["2021-09-02T12:00:00.000+07:00",206.80],["2021-09-02T13:00:00.000+07:00",206.81],["2021-09-02T14:00:00.000+07:00",206.82],["2021-09-02T15:00:00.000+07:00",206.83],["2021-09-02T16:00:00.000+07:00",206.83],["2021-09-02T17:00:00.000+07:00",206.83],["2021-09-02T18:00:00.000+07:00",206.83],["2021-09-02T19:00:00.000+07:00",206.83],["2021-09-02T20:00:00.000+07:00",206.83],["2021-09-02T21:00:00.000+07:00",206.84],["2021-09-02T22:00:00.000+07:00",206.85],["2021-09-02T23:00:00.000+07:00",206.86],["2021-09-03T00:00:00.000+07:00",206.87],["2021-09-03T01:00:00.000+07:00",206.89],["2021-09-03T02:00:00.000+07:00",206.91],["2021-09-03T03:00:00.000+07:00",206.93],["2021-09-03T04:00:00.000+07:00",206.95],["2021-09-03T05:00:00.000+07:00",206.96],["2021-09-03T06:00:00.000+07:00",206.97],["2021-09-03T07:00:00.000+07:00",206.98],["2021-09-03T08:00:00.000+07:00",207.00],["2021-09-03T09:00:00.000+07:00",207.02],["2021-09-03T10:00:00.000+07:00",207.04],["2021-09-03T11:00:00.000+07:00",207.06],["2021-09-03T12:00:00.000+07:00",207.08],["2021-09-03T13:00:00.000+07:00",207.11],["2021-09-03T14:00:00.000+07:00",207.14],["2021-09-03T15:00:00.000+07:00",207.17],["2021-09-03T16:00:00.000+07:00",207.18],["2021-09-03T17:00:00.000+07:00",207.19],["2021-09-03T18:00:00.000+07:00",207.20],["2021-09-03T19:00:00.000+07:00",207.20],["2021-09-03T20:00:00.000+07:00",207.20],["2021-09-03T21:00:00.000+07:00",207.20],["2021-09-03T22:00:00.000+07:00",207.19],["2021-09-03T23:00:00.000+07:00",207.18],["2021-09-04T00:00:00.000+07:00",207.17],["2021-09-04T01:00:00.000+07:00",207.18],["2021-09-04T07:00:00.000+07:00",207.30]]}]
Blockquote
I have tried to get this data with VBA but unsuccess, somebody can help me with VBA code to get data from "data".
This the code i have used:
Public Sub exceljson()
Dim http As Object, JSON As Object, i As Integer
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", "https://cdh.vnmha.gov.vn/KiWIS/KiWIS?service=kisters&type=queryServices&request=getTimeseriesValues&datasource=0&format=dajson&ts_id=96643010&period=P3D", False
http.Send
Set JSON = ParseJson(http.responseText)
i = 2
For Each Item In JSON
Sheets(1).Cells(i, 1).Value = Item("data")
i = i + 1
Next
MsgBox ("complete")
End Sub
This is the structure of how to get a Xero Access Token from an OAuth 2.0 Xero Authorization Code according to https://developer.xero.com/documentation/oauth2/auth-flow
POST https://identity.xero.com/connect/token
authorization: "Basic " + base64encode(client_id + ":" + client_secret)
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code
&code=xxxxxx
&redirect_uri=https://myapp.com/redirect
I have created the following vb.net framework 4.6.1 Winforms code:
Dim base64Decoded As String = xeroClientId & ":" & xeroClientSecret
Dim base64Encoded As String
Dim data As Byte()
data = System.Text.ASCIIEncoding.ASCII.GetBytes(base64Decoded)
base64Encoded = System.Convert.ToBase64String(data)
Dim Basic As String = "Basic " & base64Encoded
Dim getTenant As RestClient = New RestClient("https://identity.xero.com/connect/token")
getTenant.Timeout = -1
Dim request = New RestRequest(Method.POST)
request.AddHeader("authorization", Basic)
request.AddHeader("Content-Type", "application/x-www-form-urlencoded")
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls
request.AddParameter("grant_type", "authorization_code", ParameterType.RequestBody)
request.AddParameter("code", xeroCode, ParameterType.RequestBody)
request.AddParameter("redirect_uri", String.Format("http://localhost:5000/"), ParameterType.RequestBody)
Dim response As IRestResponse = getTenant.Execute(request)
This code gives me the error
"unsupported_grant_type"
Isn't request.AddParameter("grant_type", "authorization_code", ParameterType.RequestBody) the right way of creating grant_type=authorization_code in the request body? What am I missing?
Any help would be appreciated.
If ServerVersion > localVersion Then
Net.ServicePointManager.DefaultConnectionLimit = 20
Dim url As New Uri(sUrlToReadFileFrom)
Dim request As System.Net.HttpWebRequest = CType(System.Net.WebRequest.Create(url), System.Net.HttpWebRequest)
Dim response As System.Net.HttpWebResponse = CType(request.GetResponse(), System.Net.HttpWebResponse)
response.Close()
Dim iSize As Int64 = response.ContentLength
Dim iRunningByteTotal As Int64 = 0
Using client As New System.Net.WebClient()
Using streamRemote As System.IO.Stream = client.OpenRead(New Uri(sUrlToReadFileFrom))
Using streamLocal As Stream = New FileStream(sFilePathToWriteFileTo, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None)
Dim iByteSize As Integer = 0
Dim byteBuffer(iSize - 1) As Byte
iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)
Do While iByteSize > 0
streamLocal.Write(byteBuffer, 0, iByteSize)
iRunningByteTotal += iByteSize
Dim dIndex As Double = CDbl(iRunningByteTotal)
Dim dTotal As Double = CDbl(byteBuffer.Length)
Dim dProgressPercentage As Double = (dIndex / dTotal)
Dim iProgressPercentage As Integer = CInt(Math.Truncate(dProgressPercentage * 100))
bgDownloader.ReportProgress(iProgressPercentage)
iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)
Loop
streamLocal.Close()
End Using
streamRemote.Close()
End Using
End If
Using the above code in a BackgroundWorker on a VB.NET WPF Project. An error occurs when I try to start the code.
The calling thread cannot access this object because a different thread owns it.
This code works perfectly in WinForms project without any edits/modifications.
Thanks to #Cruled for providing the clue. It has been fixed.
What I did is add invokes on all things needs updating.
This question already has answers here:
Attach a file from MemoryStream to a MailMessage in C#
(8 answers)
Closed 5 years ago.
I'm migrating web servers and rewriting some of our applications (vb.net environment). In doing so, I have come across a dilema, and would greatly appreciate some help.
I can successfully pull a .pdf file out of a database and display it:
Dim iID As Integer
Dim bPDF As Byte()
iID = Convert.ToInt32(Request.QueryString("Id"))
bPDF = CodeMod.GetPdfBytes(iID)
Response.ContentType = "application/pdf"
Response.OutputStream.Write(bPDF, 0, bPDF.Length)
---------------------------------
Public Function GetPdfBytes(ByVal id As Int32) As Byte()
Dim SQLcon As New SqlClient.SqlConnection
Dim SQLcmd As New SqlClient.SqlCommand
Dim dt As New DataTable
SQLcon.ConnectionString = sConnection("pdfStore")
SQLcmd.CommandText = "[DOIMSQL,1433].[DOI_PDF_Storage].dbo.sel_pdf_id"
SQLcmd.CommandType = CommandType.StoredProcedure
SQLcmd.Parameters.Add("#pdf_id", SqlDbType.VarChar).Value = id
SQLcmd.Connection = SQLcon
SQLcon.Open()
dt.Load(SQLcmd.ExecuteReader)
SQLcon.Close()
GetPdfBytes = DirectCast(dt.Rows(0)("pdf_file"), Byte())
End Function
AND I can successfully send an email with a file attachment:
CodeMod.sendMail(strTo, strFrom, "Test Email", "Test Content",, Server.MapPath("/Test/TEST.pdf"))
---------------------------------
Public Sub sendMail(strTo As String, strFrom As String, strSubject As String, strMsg As String, Optional ByVal strCc As String = "", Optional ByVal file As String = "")
Dim oMMsg As New Net.Mail.MailMessage()
oMMsg.From = New MailAddress(strFrom)
oMMsg.To.Add(strTo)
oMMsg.Subject = strSubject
oMMsg.Body = strMsg
oMMsg.IsBodyHtml = True
If file <> "" Then oMMsg.Attachments.Add(New Attachment(file))
Dim client As New SmtpClient()
client.Host = "correct.information"
client.Port = 25
client.Send(oMMsg)
End Sub
What I need to do is to marry these two capabilities. I need to retrieve a .pdf from out of the database and send it as an email attachment...
...without ever writing the file to the file structure.
If I get it right, you can write that PDF into a memory stream and make an attachment directly from the memory stream. There is an existing separate question on how to attach from memory stream
Attach a file from MemoryStream to a MailMessage in C#
I have built working VB.net code that uploads multiple images to the server using Plupload. I am using an HTTPHandler (FileUpload.ashx) to do the uplading and want to add a SQL Statement that will insert each of the images File Names to my SQL Database. I have tried just adding the SQL to the Handler, but when I do I get 4 database entries for each iamge that is uploaded. I really dont understand why and need some guidance. Thanks for your time in advance.
Pertainant HANDLER code:
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim chunk As Integer = If(context.Request("chunk") IsNot Nothing, Integer.Parse(context.Request("chunk")), 0)
Dim fileName As String = If(context.Request("name") IsNot Nothing, context.Request("name"), String.Empty)
Dim fileUpload As HttpPostedFile = context.Request.Files(0)
Dim uploadPath = context.Server.MapPath("Upload")
Using fs = New FileStream(Path.Combine(uploadPath, fileName), If(chunk = 0, FileMode.Create, FileMode.Append))
Dim buffer = New Byte(fileUpload.InputStream.Length - 1) {}
fileUpload.InputStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, buffer.Length)
End Using
context.Response.ContentType = "text/plain"
context.Response.Write("Success")
EXP: SQL insert
Dim conn As SqlClient.SqlConnection = New SqlClient.SqlConnection(DBCONN)
Dim command As SqlClient.SqlCommand = New SqlClient.SqlCommand("W2_InsertPhoto " & fileName, conn)
Dim rs As SqlClient.SqlDataReader
conn.Open()
rs = command.ExecuteReader()
rs.Close()
rs = Nothing
conn.Close()
conn = Nothing
If you are using chunks then make sure that you fire your SQL aster the last chunk has been saved
For example.
chunk = If(context.Request("chunk") IsNot Nothing, Integer.Parse(context.Request("chunk")), 0)
chunks = If(context.Request("chunks") IsNot Nothing, Integer.Parse(context.Request("chunks")) - 1, 0)
If (chunk = chunks) Then
'Upload is complete, Save to DB here or whatever
end if
-1 is used on CHUNKS because chunks is -1 from the last chunk, if that makes sense.
To get the file name all you need to add in your handler.ashx is..
fileName = If(context.Request("name") IsNot Nothing, context.Request("name"), String.Empty)
In order to get unique fileName from Pluplaod across to your handler, you need to tell Plupload(on the client) to use unique names.
var uploader = new plupload.Uploader({
runtimes: 'html5,flash,silverlight,html4',
max_file_size: '20mb',
url: '../handler.ashx',
chunk_size: '100kb',
unique_names: true,
multipart_params: { imageType: $('#myDiv').attr("MyIMageType"), custom: 'This is static custom text' },
In your handler you call the 'name' request again and you will have the unqie names that pluplaoder made.. also to request the data in the multipart you do as usual request
PictureType = If(context.Request("imageType") IsNot Nothing, [Enum].Parse(GetType(PictureType), context.Request("imageType")), Nothing)
Dim myCustom as String = If(context.Request("custom") IsNot Nothing, context.Request("custom"))
In response to your SQL you need to encapsulate the file name withing ' otherwise spaces and special characters will break the SQLCommand, because SQL will think its another variable or command instead of treating it purely as a string. This is also a common problem for SQL Injection.. Allowing hackers to inject code because of code like this.
ppumpkin, I dont think I am explaining myself well. Sorry for what I am sure is lamens terms, I am new to plupload and handlers all at the same time.
I am using unique naming as "false" because I need to retain the original name of each file. I am currently naming the filenames correctly on upload to server, but for my SQL insert I need those same names inserted. If I try and use the FileName that I declared (context.Request("name")) as a value in my SQL Statement I immediately get an error and no inserted value. If I use a static value for filename just to test, it inserts just fine, but of course its the same name for each file I upload.
Including your updates, this what I currently have for my handler and clients script.
Handler:
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim chunk As Integer = If(context.Request("chunk") IsNot Nothing, Integer.Parse(context.Request("chunk")), 0)
Dim chunks As Integer = If(context.Request("chunks") IsNot Nothing, Integer.Parse(context.Request("chunks")) - 1, 0)
Dim fileName As String = If(context.Request("name") IsNot Nothing, context.Request("name"), String.Empty)
If (chunk = chunks) Then
Dim conn As SqlClient.SqlConnection = New SqlClient.SqlConnection(mdata.DBCONN)
Dim command As SqlClient.SqlCommand = New SqlClient.SqlCommand("W2_InsertPhoto 12345," & **fileName**, conn)
Dim rs As SqlClient.SqlDataReader
conn.Open()
rs = command.ExecuteReader()
rs.Close()
rs = Nothing
conn.Close()
conn = Nothing
End If
Dim fileUpload As HttpPostedFile = context.Request.Files(0)
Dim uploadPath = context.Server.MapPath("Upload")
Using fs = New FileStream(Path.Combine(uploadPath, fileName), If(chunk = 0, FileMode.Create, FileMode.Append))
Dim buffer = New Byte(fileUpload.InputStream.Length - 1) {}
fileUpload.InputStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, buffer.Length)
End Using
End Sub
My client Script:
<script type="text/javascript">
// Convert divs to queue widgets when the DOM is ready
$(function () {
$("#uploader").pluploadQueue({
// General settings,silverlight,browserplus,html5gears,
runtimes: 'flash',
url: 'FileUpload.ashx',
max_file_size: '10mb',
chunk_size: '1mb',
unique_names: false,
// Specify what files to browse for
filters: [{ title: "Image files", extensions: "jpg,jpeg,gif,png,bmp"}],
// Flash settings
flash_swf_url: 'assets/resources/plupload.flash.swf',
// Silverlight settings
silverlight_xap_url: 'assets/resources/plupload.silverlight.xap',
init: {
FileUploaded: function (up, file, info) {
}
}
});
// Client side form validation
$('form').submit(function (e) {
var uploader = $('#uploader').pluploadQueue();
// Validate number of uploaded files
if (uploader.total.uploaded == 0) {
// Files in queue upload them first
if (uploader.files.length > 0) {
// When all files are uploaded submit form
uploader.bind('UploadProgress', function () {
if (uploader.total.uploaded == uploader.files.length)
$('form').submit();
});
uploader.start();
} else
alert('You must at least upload one file.');
e.preventDefault();
}
});
//tweak to reset the interface for new file upload
$('#btnReset').click(function () {
var uploader = $('#uploader').pluploadQueue();
//clear files object
uploader.files.length = 0;
$('div.plupload_buttons').css('display', 'block');
$('span.plupload_upload_status').html('');
$('span.plupload_upload_status').css('display', 'none');
$('a.plupload_start').addClass('plupload_disabled');
//resetting the flash container css property
$('.flash').css({
position: 'absolute', top: '292px',
background: 'none repeat scroll 0% 0% transparent',
width: '77px',
height: '22px',
left: '16px'
});
//clear the upload list
$('#uploader_filelist li').each(function (idx, val) {
$(val).remove();
});
});
});
</script>