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_
Related
In the following code,
I get a run time error of
"Input string was not in a correct format." after oCommand.ExecuteReader().
oCommand.CommandText = "CheckOutItem";
oCommand.CommandType = System.Data.CommandType.StoredProcedure;
oCommand.Parameters.AddWithValue("#OrderID", OrderID);
oCommand.Parameters.AddWithValue("#GivenLargeSizeName", Enum.GetName(typeof(Size), Size.REGULAR));
oCommand.Parameters.AddWithValue("#GivenSmallSizeName", Enum.GetName(typeof(Size), Size.SMALL));
oCommand.Parameters.AddWithValue("#Latitude",oOrder.OrderTimeLocation.Location.latitude);
oCommand.Parameters.AddWithValue("#Longitude",oOrder.OrderTimeLocation.Location.longitude);
oCommand.Parameters.AddWithValue("#ListingID", MySqlDbType.Int64);
oCommand.Parameters.AddWithValue("#Quantity", MySqlDbType.Int16);
oCommand.Parameters.AddWithValue("#Size", MySqlDbType.VarChar);
oCommand.Parameters.AddWithValue("#DeliveryMethod", MySqlDbType.VarChar);
foreach (var OrderItem in oOrder.OrderItems)
{
oCommand.Parameters["#ListingID"].Value = OrderItem.ListingID;
oCommand.Parameters["#Quantity"].Value = OrderItem.Quantity;
oCommand.Parameters["#Size"].Value = Enum.GetName(typeof(Size), OrderItem.Size);
oCommand.Parameters["#DeliveryMethod"].Value = Enum.GetName(typeof(DeliverMethod), OrderItem.DeliveryPickupMethod);
using (var reader = oCommand.ExecuteReader())
{
while (reader.Read())
{
Int64 OrderItemID = Convert.ToInt64(reader["#ORDER_ITEM_ID"]);
Int64 OrderItemStatusID = Convert.ToInt64(reader["#ORDER_ITEM_STATUS_ID"]);
Int64 OrderItemPriceID = Convert.ToInt64(reader["#ORDER_ITEM_PRICE_ID"]);
TotalOrderCostFromDB = TotalOrderCostFromDB + Convert.ToDecimal(reader["#TOTAL_ORDER_COST"]);
}
}
}
if I use statements like
oCommand.Parameters.AddWithValue("#ListingID",OrderItem.ListingID)
works fine but I can not loop.
All the values I am assigning are correct in debugging and no nulls or weird stuff getting into .Value.
Since I get the correct answer in AddWithValue method, I don't think I have any issue with StoredPoocedure.
Is there a better approach to loop for this purpose?
After some debugging, I was able to narrow down the issues to last two lines
oCommand.Parameters.AddWithValue("#Size", MySqlDbType.VarChar);
oCommand.Parameters.AddWithValue("#DeliveryMethod", MySqlDbType.VarChar);
If I initialize this with a dummy string, everything is fine. But initializing with VarChar or String cause problems.
For my understanding, following returns a string right?
Enum.GetName(typeof(Size), OrderItem.Size)
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.
I am attempting to create a VBA script for Microsoft Access that pulls titles (such as Mr., Mrs.,Dr.,etc.) from a name field and then return a cleaned specific version of that title. I tried to make a multidimensional array with the title in one column and the cleaned title in another column but when I attempt to compile the script, I get a syntax error. I know the syntax error is because of the multidimensional array as I based this off a previous script that used to just find the old titles and it worked fine. What am I missing that's causing this to be a syntax error? Did I not call the multidimensional array correctly? Admittedly I am new to VBA scripts and rusty in programming in general so forgive me if I'm missing something simple.
Public Function findTitles(inName) As String
' Returns cleaned up titles
Dim strName As String
Dim strTitle As String
Dim Titles As Variant
Titles = Array(Array("Ms", "Ms."), Array("Miss ", "Miss"), Array("Mrs", "Mrs."), Array("Mr", "Mr."), Array("Master", "Master"), Array("Rev", "Rev."), Array("Reverend", "Reverend"), Array("Fr", "Fr."),Array("Father", "Father"), Array("Dr", "Dr."), Array("Doctor", "Doctor"), Array("Atty", "Atty."), Array("Attorney", "Attorney"),Array("Prof", "Prof."), Array("Professor", "Professor"), Array("Hon", "Hon."), Array("Honorable", "Honorable"), Array("Pres", "Pres."), Array("President", "President"), Array("Gov", "Gov."), Array("Governor", "Governor"))
Dim I
I = 0
strTitle = ""
'Compare input to list of Titles
Do
If inName Like Titles(I, 0) & " *" Then
strTitle = Titles(I, 1)
Else
I = I + 1
End If
Loop While (strTitle = "" And I < UBound(Titles))
cleanTitles = strTitle
End Function
The problem is that your array is not multi-dimensional, but nested. The error you are likely getting is not a syntax error, but instead a "Subscript out of range." error. You need to change your array statments like so:
Titles(I, 0)
Should be
Titles(I)(0)
Additionally on your last line you have:
cleanTitles = strTitle
I think you meant:
findTitles = strTitle
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....!
I am new to Mondrian. I am using it in my project for OLAP operations.
I am testing it with Foodmart database.
The problem is that I need the OLAP operations results in JSON format.
I know that mondrian has the same structure as JSON in the form of hierarchies.
I want to generate a JSON file as an output from the result of mondrian MDX query.
The result should be similar to OLAP operations.
I don't know how to iterate over the result generated from MDX query.
Here is the code.
String connStr = "Provider=mondrian;" +
"Catalog=/WEB-INF/FoodMart.xml;" +
"JdbcDrivers=com.mysql.jdbc.Driver;" +
"Jdbc=jdbc:mysql://localhost/foodmart;" +
"jdbcUser=root;" +
"jdbcPassword=;";
String queryStr ="select {[Measures].[Unit Sales], [Measures].[Store Cost], [Measures].>Store Sales]} ON COLUMNS,"+"Crossjoin(Hierarchize(Union({[Promotion Media].[All Media]}, >[Promotion Media].[All Media].Children)), {[Product].[All Products]})
ON ROWS"+" from [Sales]"+"where [Time].[1997]";
Connection connection = DriverManager.getConnection(connStr, null);
Query query = connection.parseQuery(queryStr);
Result result = connection.execute(query);
result.print(new PrintWriter(System.out));
Actually I need to perform OLAP operations on data warehouse which is stored in MySQL.
The resulted data should be in JSON format which I will pass to D3 http://mbostock.github.com/d3 for visualizations.
For data format I have to use JSON format.
Please any suggestions how to iterate MDX result and convert it in JSON file.
I am using Pentaho Mondrian for this purpose.
Thanks.
if you are working with PHP you could use this library to transform the xmla result into Json
http://www.ibm.com/developerworks/xml/library/x-xml2jsonphp/
Here's an example of what i suppose you want to do:
Class.forName("mondrian.olap4j.MondrianOlap4jDriver"); //load the driver
Connection connection = DriverManager.getConnection("Provider=mondrian;" +
"Catalog=/WEB-INF/FoodMart.xml;" +
"JdbcDrivers=com.mysql.jdbc.Driver;" +
"Jdbc=jdbc:mysql://localhost/foodmart;" +
"jdbcUser=root;" +
"jdbcPassword=;");
OlapWrapper wrapper = (OlapWrapper) connection;
OlapConnection olapConnection = wrapper.unwrap(OlapConnection.class);
CellSet cellSet = statement.executeOlapQuery(query);
CellSetAxis rows = cellSet.getAxes().get(1); //cube rows
CellSetAxis columns = cellSet.getAxes().get(0); //cube columns
int resultSize = rows.getPositionCount() * columns.getPositionCount();
String resultValues[] = new String[resultSize];
int valueIndex = 0;
for (Position row : rows) {
for (Position column : columns) {
Cell cell = cellSet.getCell(column, row);
String cellValue = cell.getFormattedValue();
resultValues[valueIndex++] = cellValue;
}
}
Gson gson = new Gson(); //gson library instance
String resultString = gson.toJson(responseValues); //json string
olapConnection.close();
connection.close();