How to convert an Image into BLOB (Binary Large Object) format - mysql

I need a comparison between an input image with the
blob field in MySql table. so that i need to conver the image into BLOB format.
i had tried a lot in previous days but faild to achieve a good,i here by summerise the result
of my search for this comparison:
convert the image into byte array using the following code
Dim fileName As String
ListBox1.Items.Clear()
fileName = "D:\me.jpeg"
Dim fs As New FileStream(fileName, FileMode.Open, FileAccess.Read)' Create a byte array of file stream length
Dim ImageData As Byte() = New Byte(fs.Length - 1) {}'Read block of bytes from stream into the byte array
fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length))'Close the File Stream
fs.Close()
For j As Integer = 0 To ImageData.Length - 1
ListBox1.Items.Add(ImageData(j).ToString)' list out the byte array
Next
Retrive the blob field carasponds to the same field
ListBox1.Items.Clear()
mystring = "select image from blob_table where id='28' "
openconnection() ' Methode to open a mysql connection
cmd = New Odbc.OdbcCommand(mystring, myconnection)
imagebyte = cmd.ExecuteScalar
For j As Integer = 0 To imagebyte.Length - 1
ListBox2.Items.Add(imagebyte(j).ToString) ' list out the BOLB array
Next
closeconnection() ' Close the connection
Both the list boxes are shown in the image below.
Both the lists are entirely different, byte array is comparitevely very large than blob it having more than 10K values so the comparison become harder and does not give the expected result.
Is their any possibility to convert an image into blob format? through vb.net. or any other
alternate solution for this comparison
Thanks in Advance for positive response....!

Related

JSON Result object dynamically written to Excel Worksheet VBA

I am attempting to write a tabular result (columns and rows of data) from an API call into an Excel range / table.
I managed to get it working, but I'd like for this to be dynamic across data sets (my data sets can be any shape with differing field names). As can be seen in the image, I don't necessarily know that the output is 3 columns of data, but I would want to get this from the JsonResult object (it forms part of the object, but I don't know how to access / reference it).
The object also contains the column names of the data which I would like written to Excel as well (as headings), but I don't know how.
Finally I'd like to write the row data to Excel as well, but I don't know how to access these values without specific reference to them (e.g. "company_code").
TO SUMMARISE: The items in yellow in the screenshot as well as the column / field names should be dynamically read from the JsonResult object.
Any assistance would be appreciated.
JsonResult in text: "[{"company_code":"ABC","employee_code":"5","is_exception":"0"},{"company_code":"ABC","employee_code":"8","is_exception":"1"}]"
My code snippet (if it helps):
Set JsonResult = ParseJson(ParseJson(req.responseText)("results")(1)("findings"))("results")
Dim Values As Variant
ReDim Values(JsonResult.Count, 3)
Dim Value As Dictionary
Dim i As Long
i = 0
For Each Value In JsonResult
Values(i, 0) = Value("company_code")
Values(i, 1) = Value("employee_code")
Values(i, 2) = Value("is_exception")
i = i + 1
Next Value
Sheets("Sheet1").Range(Cells(1, 1), Cells(JsonResult.Count, 3)) = Values
This is what ended up working for me:
Dim Item As Dictionary
Dim i As Long, size As Long
size = UBound(JsonResult(1).Keys) + 1
[a1].Resize(, size) = JsonResult(1).Keys 'Header rows
i = 1
For Each Item In JsonResult
i = i + 1
Range("A" & i).Resize(, size) = Item.Items 'Result rows
Next Item
The keys from the collection / dictionary's first Item is used for the Header rows and the items from each item in the collection / dictionary is written to Excel after that.
Works like an absolute charm.

Convert JSON date to vb.net date format

Following is the vb.net code which reads json string and then it bulkcopy to SQL.
I am getting and error when it bulkcopy to sql server saying "Invalid Data type"
Issue is with date format of column ("idt"). If i don't include this column in SQLBulk copy then it successfully inserts rest of the data into SQL.
Dim JsonP As JObject = JObject.Parse(decodedString)
Dim SetPointerOut As JToken = JsonP("b2b")
Try
Dim i as Integer = 0
Dim j as Integer = 0
For Each itemout as Object In SetPointerOut
Dim SetPointerIn As JToken = JsonP("b2b")(i)("inv")
For Each itemin as Object In SetPointerIn
Dim SetPointerInSub As JToken = JsonP("b2b")(i)("inv")(j)("itms")
For Each iteminsub as Object In SetPointerInSub
Dim NewDRinsub As DataRow = TempDT.NewRow
NewDRinsub("ctin") = itemout("ctin")
NewDRinsub("cfs") = itemout("cfs")
NewDRinsub("val") = itemin("val")
NewDRinsub("inv_typ") = itemin("inv_typ")
NewDRinsub("pos") = itemin("pos")
NewDRinsub("idt") = itemin("idt") --- **source json has this date in format "dd-mm-yyyy"
NewDRinsub("rchrg") = itemin("rchrg")
NewDRinsub("inum") = itemin("inum")
NewDRinsub("chksum") = itemin("chksum")
TempDT.Rows.Add(NewDRinsub)
Next
j = j + 1
Next
i += 1
j = 0
Next
Using sqlBulkCopy As New SqlBulkCopy(Mycon.mConnection, SqlBulkCopyOptions.FireTriggers, Nothing)
sqlBulkCopy.DestinationTableName = "GST2_B2B"
sqlBulkCopy.ColumnMappings.Add("ctin", "PartyGSTNo")
sqlBulkCopy.ColumnMappings.Add("cfs", "CFS")
sqlBulkCopy.ColumnMappings.Add("val", "Invoice_Value")
sqlBulkCopy.ColumnMappings.Add("inv_typ", "Invoice_Type")
sqlBulkCopy.ColumnMappings.Add("pos", "StateCode")
sqlBulkCopy.ColumnMappings.Add("idt", "Invoice_Date") --- source json has this date in format "dd-mm-yyyy"
sqlBulkCopy.ColumnMappings.Add("rchrg", "ReverseCharge")
sqlBulkCopy.ColumnMappings.Add("inum", "Invoice_Number")
sqlBulkCopy.ColumnMappings.Add("chksum", "CHKSUM")
sqlBulkCopy.ColumnMappings.Add("period", "Period")
sqlBulkCopy.BulkCopyTimeout = 120
sqlBulkCopy.WriteToServer(TempDT) -- error at this stage
--- Getting error at this stage, saying "Invalid datatype", and that is because of column sqlBulkCopy.ColumnMappings.Add("idt", "Invoice_Date")
End Using
so as said, if i remove sqlBulkCopy.ColumnMappings.Add("idt", "Invoice_Date"), then it works well. I guess Bulkcopy has some issue with dateformt of "idt" column of vb.net datatable.
So, how do i resolve this dateformat issue?
how do i convert json date to vb.net format at code line marked above with comment?
Just for grins give this a shot.
NewDRinsub("idt") = Date.ParseExact(itemin("idt"), "dd-MM-yyyy", CultureInfo.InvariantCulture)
https://learn.microsoft.com/en-us/dotnet/api/system.datetime.parseexact?view=netframework-4.8#System_DateTime_ParseExact_System_String_System_String_System_IFormatProvider_

How to add each line from string to listbox vb.net

Okay my website is connected to mysql database and it reads off strings of data from the database into plain text. I want to get each line from my website and add it to a list box.
This is what I have so far.
Dim GetInfo As String = WBInfo.DownloadString("https://MyWebsite.com/test.php?id=data")
GetInfo Outputs Like:
user1:user2:user3
user2:user3:user4
user3:user4:user5
etc..
For Each line In GetInfo
Dim parts As String() = line.ToString.Split(New Char() {":"c})
ListBox1.Items.Add(parts(1))
ListBox1.Items.Add(parts(2))
ListBox1.Items.Add(parts(3))
Next
In first, use
Dim parts As String() = line.ToString.Split(":"c)
Note, the indexes of an array starts from 0. Also you can use For Each loop statement instead of indexes, for example:
For Each part As String In parts
ListBox1.Items.Add(part)
Next
To maintain performance while items are added to the ListBox use BeginUpdate() and EndUpdate() methods.

JSON.NET: Get Specific JSON Date Value

In my VB.NET project, using JSON.NET, I've got a JSON from a Web API that has a value representing a date in the yyyy-MM-ddTHH:mm:ss format, and I'd like to simply get that value.
Here's more or less what the JSON looks like:
{
"REQ_DATE": "2016-01-17T12:27:57",
"REQ_TYPE": "Vacation",
"HOURS": 500.0,
"LEAVE_TIME": "8:00 AM",
"LEAVE_DATE": "2016-01-23T00:00:00",
"DUE_TIME": "8:00 AM",
"DUE_DATE": "2016-01-24T00:00:00",
}
So I should just serialize it and do what I will with the value, right? However, when I put that key-value in a variable, the date format is automatically changed!
Dim temp As String = myJsonResult("REQ_DATE")
' temp = "1/17/2016 12:27:57 PM"
I need to have that Date as it was from the retrieved JSON. I see two ways to go about this problem: converting it to yyyy-MM-ddTHH:mm:ss manually, or using regex to directly grab the key-value pair - both of which I have had no success with.
My attempt to convert it into DateTime:
Dim tempDateTime As DateTime = DateTime.ParseExact(myJsonResult("REQ_DATE").ToString,"yyyy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture)
' Error: String is not Recognized as valid DateTime
Dim myDesiredResult As String = tempDateTime.ToString("yyyy-MM-ddTHH:mm:ss")
My attempt to use Regex:
Dim regex As Regex = New Regex("""REQ_DATE"": ""([\d\w]*)""")
Dim match As Match = regex.Match(myJsonAsString)
If match.Success Then
Dim myDesiredResult As String = match.Groups(1).Value
End If
' match is empty...
Any and all help is greatly appreciated.
I assume that myJsonResult is a JObject into which you have loaded your JSON.
Your difficulty is that Json.NET automatically recognizes strings as dates when reading and converts them to DateTime structs. Then when you later do ToString() on the value token, it comes back in c#'s "invariant culture" format rather than the original format, which in this case was ISO 8601. If you do not want this behavior, you can parse your JSON using JsonSerializerSettings.DateParseHandling = DateParseHandling.None:
Dim jsonString = "{'REQ_DATE':'2016-01-17T12:27:57','REQ_TYPE':'Vacation','HOURS':500.0,'LEAVE_TIME':'8:00 AM','LEAVE_DATE':'2016-01-23T00:00:00','DUE_TIME':'8:00 AM','DUE_DATE':'2016-01-24T00:00:00'}"
Dim settings = New JsonSerializerSettings() With { _
.DateParseHandling = DateParseHandling.None _
}
Dim myJsonResult = JsonConvert.DeserializeObject(Of JObject)(jsonString, settings)
Dim dateValue = myJsonResult("REQ_DATE")
Dim dateString = CType(dateValue, String) 'Value is 2016-01-17T12:27:57
There's no overload to JObject.Parse() that takes a JsonSerializerSettings, so you would need to use DeserializeObject. This setting eventually gets propagated to JsonReader.DateParseHandling.
Alternatively, if you are OK with Json.NET recognizing dates but would always like them to be printed in ISO 8601 format, you can re-serialize the token to JSON rather than just getting the string value:
Dim dateValue = myJsonResult("REQ_DATE")
Dim dateString = JsonConvert.SerializeObject(dateValue).Trim(""""c) 'Value is 2016-01-17T12:27:57
Prototype fiddle. Related c# question.
When you get the parsed date-string from JSON.NET it will be in your culture's format as shown in your code comment:
Dim temp As String = myJsonResult("REQ_DATE")
' temp = "1/17/2016 12:27:57 PM"
That format is "M/d/yyyy HH:mm:ss tt" so use that format for parsing. But since it is in a format for your culture, you can let DateTime check/use all the known formats using TryParse:
Dim dt As DateTime
Dim temp As String = jobj("REQ_DATE").ToString
If DateTime.TryParse(temp, dt) Then
'dt is good to use!
Console.WriteLine(dt.ToString)
' Prints: 1/17/2016 12:27:57 PM
End If
Dim myDesiredResult As String = dt.ToString("yyyy-MM-ddTHH:mm:ss")
' result: "2016-01-17T12:27:57"
If you want to specify the format (it would be better to use TryParseExact):
dt = DateTime.ParseExact(temp, "M/d/yyyy HH:mm:ss tt",
CultureInfo.InvariantCulture)
Console.WriteLine(dt.ToString())
' Also prints: 1/17/2016 12:27:57 PM
Dates dont have a format, so it cant change, but it may display differently for your culture settings. You can display it any way you want, it is still the same date:
Console.WriteLine(dt.ToString("HH yyyy MM mm dd"))
Console.WriteLine(dt.ToString("yyyy-MM-ddTHH:mm:ss"))
Console.WriteLine(dt.ToString("MM/d/yyyy HH:mm:ss tt"))
Answering my own question. I've got it to work simply by doing DateTime.Parse on the JObject, then doing ToString to my desired format.
Dim temp As String = myRequest("REQ_DATE").ToString
Dim tempDateTime As DateTime = DateTime.Parse(temp.ToString)
Dim myDesiredResult As String = tempDateTime.ToString("yyyy-MM-ddTHH:mm:ss")
I used dbc's answer in my code as it is more elegant.

VBA Access - Array via textbox

At the moment all my arrays are implemented in the vba code. This works fine
Dim COST As String
Dim GAT As String
Dim OND As String
COST = "C:\Users\update\COST.xlsb"
GAT = "C:\Users\BACKUP\GAT.xlsb"
OND = "C:\Users\BACKUP\OND.xlsb"
MyArray = Array(COST, GAT, OND)
However I would like to select the above arrays from a textbox via a form
Below code works but I have to implement the file path
MyArray = Array(Forms![LAYOUT_F]![Update_F])
with file path
MyArray = Array("C:\Users\BACKUP\" & Forms![LAYOUT_F]![Update_F])
Using the above will require me to be file name specific and doesn't take into account arrays plus the file paths are different
Is there a way of selecting declared arrays from a textbox
I would use a multi-line textbox, where the user e.g. enters
C:\Users\update\COST.xlsb
C:\Users\BACKUP\GAT.xlsb
and then use the Split() function on the line breaks:
MyArray = Split(Me!myTextbox, vbCrLf)
But I my have misunderstood your question - not sure what you mean by "selecting declared arrays from a textbox".