Why sub json contains backslashes - json

I need To Build json of the following structure:
[{
Id: M1
Name: Menu1
Checked: True
Children:[
{Id: I1 , Name: Item1 , Checked: true, view:true , write:true},
{Id: I2 , Name: Item2 , Checked: true, view:true , write:true},
.. etc
]
},
{
Id: M2
Name: Menu2
Checked: True
Children:[
{Id: I1 , Name: Item1 , Checked: true, view:true , write:true},
{Id: I2 , Name: Item2 , Checked: true, view:true , write:true},
.. etc
]
} , etc..
]
I'm Using Vb.Net , SQl Server To get the menus and Items (objects) from the database and convert the data to json string using this code:
'Get Menus
Dim menus = DataFactory.Instance.GetMenusAndObjects(connectionString)
'Create JSON String
Dim jsonSerializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer()
Dim json As String = "["
For Each m In menus
Dim children As String = "["
Dim menu_checked As Boolean = True
For Each obj In m.Objects
Dim checked As Boolean = True
Dim view As Boolean = True
Dim write As Boolean = True
Dim link = DataFactory.Instance.GetProfileObjectLink(connectionString, profile_code, obj.ObjectCode)
If IsNothing(link) Then
view = False
write = False
checked = False
menu_checked = False
Else
If link.AllowToView.Equals("N") Then
view = False
menu_checked = False
End If
If link.AllowToModify.Equals("N") Then
write = False
menu_checked = False
End If
End If
children &= jsonSerializer.Serialize(New With {Key .Id = obj.ObjectCode,
.Name = obj.ObjectDesc,
.Checked = checked,
.View = view,
.Write = write}) & ","
Next
children &= "]"
json &= jsonSerializer.Serialize(New With {Key .Id = m.MenuCode,
.Name = m.MenuName,
.Checked = menu_checked,
.Children = children}) & ","
Next
If json.Length > 1 Then
json = json.Substring(0, json.Length - 1)
End If
json &= "]"
A Sample of the Resulted Json string in vb.Net:
[{"Id":"APPLN","Name":"Application","Checked":false,"Children":"
[{\"Id\":\"CUSTOMER_SCR\",\"Name\":\"62- Clients/
Customers\",\"Checked\":true,\"View\":false,\"Write\":false},
{\"Id\":\"EMP_SCR\",\"Name\":\"10- Employee
Manager\",\"Checked\":true,\"View\":true,\"Write\":true},]"}
,]"}
Why Backslashes are added only to the json on 'Children' Property? Do you think that the double Serialization for the children parameter is causing the problem? and if that's is the real reason how can I concatenate children jsons to the main json strings?

I pushed Each Children into a List Of Object then I converted the list to Array after that I serialized the main json, The Code:
Imports System.Web
Imports System.Web.Services
Imports System.Web.Script.Serialization
Public Class GetMenusAndObjects
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "text/plain"
'Get parameters
Dim profile_code = context.Request("profile_code")
Dim connectionString As String = UserIdentity.ClientConfig.ConnectionString
'Get Profiles
Dim menus = DataFactory.Instance.GetMenusAndObjects(connectionString)
'Create JSON String
Dim jsonSerializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer()
Dim json As String = "["
For Each m In menus
' Dim children As String = "["
Dim children = New List(Of Object)
Dim menu_checked As Boolean = True
For Each obj In m.Objects
Dim checked As Boolean = True
Dim view As Boolean = True
Dim write As Boolean = True
Dim link = DataFactory.Instance.GetProfileObjectLink(connectionString, profile_code, obj.ObjectCode)
If IsNothing(link) Then
view = False
write = False
checked = False
menu_checked = False
Else
If link.AllowToView.Equals("N") Then
view = False
menu_checked = False
End If
If link.AllowToModify.Equals("N") Then
write = False
menu_checked = False
End If
End If
children.Add(New With {.Id = obj.ObjectCode,
.Name = obj.ObjectDesc,
.Checked = checked,
.View = view,
.Write = write
})
'children &= jsonSerializer.Serialize(New With {Key .Id = obj.ObjectCode,
' .Name = obj.ObjectDesc,
' .Checked = checked,
' .View = view,
' .Write = write}) & ","
Next
'children &= "]"
json &= jsonSerializer.Serialize(New With {Key .Id = m.MenuCode,
.Name = m.MenuName,
.Checked = menu_checked,
.Children = children.ToArray()}) & ","
Next
If json.Length > 1 Then
json = json.Substring(0, json.Length - 1)
End If
json &= "]"
'Return JSON in response
context.Response.Write(json)
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class

Related

SSIS 2016 SMO Transfer error: An error occured while transferring data. See inner exception for details

We are using SMO to transfer tables over from one server to the other on SQL Server 2016.
For a while now, the transfer succeeds only one out of 3 times on 1 server only, and we always get the same error message, which doesn't say much: An error occured while transferring data. See inner exception for details.
That same package has been deployed to our 4 environments (Dev, Test, Qa and Prod) and is running everyday. However, we only get that problem in Test.
Our DBAs are not doing much to help us find the reason why that appends. Can you please give me a hint on where to look at? That SSIS package hasn't been updated for a long time, and the built version is the same in all environment.
Here is our .vb script in the package:
Public Sub Main()
'
' Source and Destination Servers
'
' MsgBox(Dts.Variables("User::SourceServer").Value.ToString)
Dim srvSourceName As String = Dts.Variables("SourceServer").Value.ToString '"brdsqldev"
Dim srvDestinationName As String = Dts.Variables("DestinationServer").Value.ToString '"brdsqldev"
Dim bt(0) As Byte
'
' Source and Destination Databases
'
Dim dbSourceName As String = Dts.Variables("SourceDB").Value.ToString
Dim dbDestinationName As String = Dts.Variables("DestinationDB").Value.ToString
Try
Dts.Log("The Transfer starts", 0, bt)
Dts.Log("Transfer starts with tables", 0, bt)
Dts.Log("Transfer starts with tables" & srvSourceName, 0, bt)
Dts.Log("Transfer starts with tables" & srvDestinationName, 0, bt)
Dts.Log("Transfer starts with tables" & dbSourceName, 0, bt)
Dts.Log("Transfer starts with tables" & dbDestinationName, 0, bt)
' TableExists()
Transfer(srvSourceName, srvDestinationName, dbSourceName, dbDestinationName, CType(Dts.Variables.Item("myDataTable").Value, System.Data.DataTable), TransferObjectType.Table)
' Transfer(srvSourceName, srvDestinationName, dbSourceName, dbDestinationName, CType(Dts.Variables.Item("myDataViews").Value, System.Data.DataTable), TransferObjectType.View)
Dts.Log("Transfer done with tables", 0, bt)
Dts.Log("The Transfer ran successfully", 0, bt)
Dts.TaskResult = ScriptResults.Success
'MessageBox.Show("The transfer ran successfully.")
Catch ex As Exception
Dts.Events.FireError(99, "", ex.Message.ToString(), "", -1)
OutPutError(ex)
Dts.TaskResult = ScriptResults.Failure
'MessageBox.Show("The transfer was aborted.")
End Try
End Sub
Private Sub Transfer(ByVal srvSourceName As String, ByVal srvDestinationName As String, ByVal dbSourceName As String, ByVal dbDestinationName As String, ByVal dataTableToTransfer As DataTable, ByVal type As TransferObjectType)
Try
Dim srcsrv As Server
srcsrv = New Server(srvSourceName)
Dim dbSource As Database
dbSource = srcsrv.Databases(dbSourceName)
Dim dessrv As Server
dessrv = New Server(srvDestinationName)
Dim dbDestination As Database
dbDestination = dessrv.Databases(dbDestinationName)
Dim oleDA As New OleDbDataAdapter
Dim dt As New DataTable
Dim row As DataRow
Dim sMsg As String
Dim xfr As Transfer
Dim bt(0) As Byte
Dts.Log("Transfer Subroutine starts ...", 0, bt)
xfr = New Transfer(dbSource)
xfr.CopyAllTables = False
xfr.Options.WithDependencies = False
xfr.Options.ContinueScriptingOnError = False
xfr.CopyAllRoles = False
xfr.CopyAllLogins = False
xfr.CopyAllDatabaseTriggers = False
xfr.CopyAllDefaults = False
xfr.CopyAllPartitionFunctions = False
xfr.CopyAllObjects = False
xfr.CopyAllPartitionFunctions = False
xfr.CopyAllPartitionSchemes = False
xfr.CopyAllRules = False
xfr.CopyAllSchemas = False
xfr.CopyAllSqlAssemblies = False
xfr.CopyAllStoredProcedures = False
xfr.CopyAllSynonyms = False
xfr.CopyAllUserDefinedAggregates = False
xfr.CopyAllUserDefinedDataTypes = False
xfr.CopyAllUserDefinedFunctions = False
xfr.CopyAllUserDefinedTypes = False
xfr.CopyAllUsers = False
xfr.CopyAllViews = False
xfr.CopyAllXmlSchemaCollections = False
xfr.CopySchema = True
xfr.DestinationDatabase = dbDestination.Name
xfr.DestinationServer = dessrv.Name
xfr.DestinationLoginSecure = True
xfr.DropDestinationObjectsFirst = False
Select Case type
Case TransferObjectType.Table
xfr.CopyData = True
Case TransferObjectType.View
xfr.CopyData = False
Case Else
Dts.Log("Unknown object transfer type. (-99)", -99, bt)
Dts.TaskResult = ScriptResults.Failure
'Throw New Exception("Unknown object transfer type.")
End Select
dt = dataTableToTransfer
Dts.Log("Transfer Subroutine just before Row Count...", 0, bt)
If dt.Rows.Count > 0 Then
Dts.Log("Transfer Row Count > 0...", 0, bt)
For Each row In dt.Rows
Dim tblSourceName As String
Dim tblSourceSchema As String
tblSourceSchema = row("transferschema").ToString()
tblSourceName = row("transferobject").ToString
Select Case type
Case TransferObjectType.Table
xfr.ObjectList.Add(dbSource.Tables(tblSourceName.ToString, tblSourceSchema.ToString))
Case TransferObjectType.View
xfr.ObjectList.Add(dbSource.Views(tblSourceName.ToString, tblSourceSchema.ToString))
Case Else
Dts.Events.FireError(99, "Transfer Object", "Unknows object type", "", -1)
Dts.TaskResult = ScriptResults.Failure
'Throw New Exception("Unknown object transfer type.")
End Select
Next
Dts.Events.FireInformation(1, "", "Just before transfering data", "", -1, False)
xfr.TransferData()
End If
Catch ex As InternalSmoErrorException
Dim bt(0) As Byte
Dts.Events.FireError(99, "Transfer Objects", ex.Message.ToString(), "", -1)
OutPutError(ex)
Dts.TaskResult = ScriptResults.Failure
End Try
End Sub
Private Sub OutPutError(ex As Exception)
Dim ErrorLogDir As String
Dim OutPutFileName As String
ErrorLogDir = System.IO.Path.GetDirectoryName(Dts.Connections("ExportNightlyTransfer.xml").ConnectionString.ToString())
OutPutFileName = ErrorLogDir + "\\" + Dts.Variables("PackageName").Value.ToString() + "ErrorReport" + Now.ToString("yyyyMMddHHmmss") + ".txt"
Using sw As StreamWriter = New StreamWriter(OutPutFileName)
sw.WriteLine(Now.ToString())
sw.WriteLine("Package Name: " + Dts.Variables("PackageName").Value.ToString())
sw.WriteLine("Task Name: " + Dts.Variables("TaskName").Value.ToString())
sw.WriteLine(ex.Message.ToString())
sw.WriteLine(ex.GetBaseException.ToString())
sw.WriteLine(ex.StackTrace.ToString())
End Using
End Sub
Thanks in advance for your help.
Mylene
By adding the Catch innerException code, I was able to get specific information about the error.
Catch ex As Exception
Dts.Events.FireError(99, "", ex.Message.ToString(), "", -1)
OutPutError(ex)
If ex.InnerException IsNot Nothing Then
Dts.Events.FireError(99, "", ex.InnerException.Message.ToString(), "", -1)
OutPutError(ex.InnerException.Message.ToString())
End If
Dts.TaskResult = ScriptResults.Failure
'MessageBox.Show("The transfer was aborted.")
End Try
Problem solved!! Thank you :-)

extract element from an array

Hi I asked the similar question before: I have a large JSON file but the information I need is only small part of it. However, that part is a two dimensional array from "text"."size" part.Is any way I can loop each array and and get the number from what I have already?
{"widget": { "debug": "on", "window": { "title": "Sample Konfabulator Widget", "name": "main_window", "width": 500, "height": 500 }, "image": { "src": "Images/Sun.png", "name": "sun1", "hOffset": 250, "vOffset": 250, "alignment": "center" }, "text": { "data": "Click Here", "size": [[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14]], "style": "bold", "name": "text1", "hOffset": 250, "vOffset": 100, "alignment": "center", "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;" } } }
I was taught from someone(thank you!) to use the following code
Option Explicit
Public Sub GetInfo()
Dim strJSON As String, json As Object, rowNumber As Long
Application.ScreenUpdating = False
Const PATH As String = "C:\Users\User\Desktop\test.JSON"
strJSON = GetJSONFromFile(PATH)
Set json = JsonConverter.ParseJson(strJSON)
Set json = json("widget")("text")
Dim key As Variant
With ThisWorkbook.Worksheets("Sheet1")
For Each key In json
rowNumber = rowNumber + 1
.Cells(rowNumber, 1) = key
.Cells(rowNumber, 2) = json(key)
Next key
End With
Application.ScreenUpdating = True
End Sub
Many Thanks
Seeing expected output would help. If you are simply after the items within the collection of collections returned by JsonConverter.ParseJson(strJSON)("widget")("text")("size") then the following will empty them.
Option Explicit
Public Sub GetInfo()
Dim strJSON As String, json As Object, rowNumber As Long, i As Long, j As Long
Const PATH As String = "C:\Users\User\Desktop\test.JSON"
strJSON = GetJSONFromFile(PATH)
Set json = JsonConverter.ParseJson(strJSON)("widget")("text")("size") '<collection of collections
With ThisWorkbook.Worksheets("Sheet1")
For i = 1 To json.Count
For j = 1 To json(i).Count
rowNumber = rowNumber + 1
.Cells(rowNumber, 1) = json(i)(j)
Next
Next
End With
End Sub
Public Function GetJSONFromFile(ByVal PATH As String) As String
Dim fso As Object, f As Object, outputString As String
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(PATH)
Do Until f.AtEndOfStream
outputString = f.ReadAll()
Loop
f.Close
GetJSONFromFile = outputString
End Function
JSON structure:
You can see the path down to the collection of collections in the JSON structure below. The {} are dictionaries and the [] are collections.

Write partial data using VBA

I have a large JSON file but the information I need is only a small part of it. Is there any way I can extract the part I want and write to an Excel sheet instead of writing the whole file? Please see the following example. I only want to extract the "text" part
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}
}
If it is a JSON file you can read as follows and empty into sheet
Option Explicit
Public Sub GetInfo()
Dim strJSON As String, json As Object, rowNumber As Long
Application.ScreenUpdating = False
Const PATH As String = "C:\Users\User\Desktop\test.JSON"
strJSON = GetJSONFromFile(PATH)
Set json = JsonConverter.ParseJson(strJSON)
Set json = json("widget")("text")
Dim key As Variant
With ThisWorkbook.Worksheets("Sheet1")
For Each key In json
rowNumber = rowNumber + 1
.Cells(rowNumber, 1) = key
.Cells(rowNumber, 2) = json(key)
Next key
End With
Application.ScreenUpdating = True
End Sub
Public Function GetJSONFromFile(ByVal PATH As String) As String
Dim fso As Object, f As Object, outputString As String
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(PATH)
Do Until f.AtEndOfStream
outputString = f.ReadAll()
Loop
f.Close
GetJSONFromFile = outputString
End Function
If you inspect the JSON you can see the the top level dictionary has a key "widget" which gives access to inner dictionaries. One of these has the key "text"; that is the one you are after and can be accessed with the syntax
Set json = json("widget")("text")
You could shorten the sub code at the top to:
Option Explicit
Public Sub GetInfo()
Dim strJSON As String, json As Object, rowNumber As Long
Application.ScreenUpdating = False
Const PATH As String = "C:\Users\HarrisQ\Desktop\test.JSON"
strJSON = GetJSONFromFile(PATH)
Set json = JsonConverter.ParseJson(strJSON)
Set json = json("widget")("text")
With ThisWorkbook.Worksheets("Sheet1")
.Cells(1, 1).Resize(json.Count) = Application.WorksheetFunction.Transpose(json.keys)
.Cells(1, 2).Resize(json.Count) = Application.WorksheetFunction.Transpose(json.Items)
End With
Application.ScreenUpdating = True
End Sub

Json data not well formated error

json data not binding into table
controller code
$http(
{
method: 'post',
url: 'Service.asmx/WPGetDS',
data: $.param({ as_sql: "select * from testtab", strConKey: "Etech" }),
dataType: 'json',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (data, status, headers, config) {
var myjson = JSON.parse(data);
$scope.dtDioSearch = myjson;
console.log(myjson);
}).error(function (data, status, headers, config) {
console.log(data);
});
Web Service Code
Public Sub WPGetDS(ByVal as_sql As String, ByVal strConKey As String)
Dim dt As New DataTable()
Dim conGlobal As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings(strConKey).ConnectionString)
Dim a(0) As String
Dim dr As DataRow
Dim dtDataTable As DataTable
If conGlobal.State = ConnectionState.Closed Then conGlobal.Open()
Dim SDA = New SqlDataAdapter(as_sql, conGlobal)
Dim DS As DataSet = New DataSet()
Dim data As New WPData
Dim js As New JavaScriptSerializer()
Dim lCmdSql, lCmdErr As New SqlCommand
Try
dtDataTable = New DataTable("Table")
Dim dcolSrNo As DataColumn
dcolSrNo = New DataColumn("SlNo")
dcolSrNo.AutoIncrement = True
dcolSrNo.AutoIncrementSeed = 1
dcolSrNo.AutoIncrementStep = 1
dtDataTable.Columns.Add(dcolSrNo)
DS.Tables.Add(dtDataTable)
SDA.Fill(DS, ("Table"))
SDA.Dispose()
data.Message = ConvertDataTableTojSonString(DS.Tables(0))
Context.Response.Write(js.Serialize(data.Message))
Catch ex As Exception
dt.Columns.Clear()
dt.Columns.Add("Error")
dr = dt.NewRow
dr.Item("Error") = ex.Message.Trim
dt.Rows.Add(dr)
DS.Tables.Add(dt)
conGlobal.Close()
data.Message = ConvertDataTableTojSonString(DS.Tables(0))
Context.Response.Write(js.Serialize(data.Message))
Finally
If conGlobal.State = ConnectionState.Open Then conGlobal.Close()
End Try
End Sub
HTML Code
<div class="table-responisive">
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Test</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="erdata in dtDioSearch track by $index">
<td>{{erdata.SlNo}}</td>
<td>{{erdata.Test}}</td>
</tr>
</tbody>
</table>
</div>
Console Json data
[{"SlNo":1,"test":"test"},{"SlNo":2,"test":"test"},{"SlNo":3,"test":"test"},{"SlNo":4,"test":"test"},{"SlNo":5,"test":"test"},{"SlNo":6,"test":"test"},{"SlNo":7,"test":"test"},{"SlNo":8,"test":"test"},{"SlNo":9,"test":"test"},{"SlNo":10,"test":"test"},{"SlNo":11,"test":"test"},{"SlNo":12,"test":"test"},{"SlNo":13,"test":"test"},{"SlNo":14,"test":"test"},{"SlNo":15,"test":"test"},{"SlNo":16,"test":"test"},{"SlNo":17,"test":"test"},{"SlNo":18,"test":"test"},{"SlNo":19,"test":"test"},{"SlNo":20,"test":"test"},{"SlNo":21,"test":"test"},{"SlNo":22,"test":"test"}]
My problem is json data not bind to the html table. in firefox there was an error shown not well-formed in console. please help...
The first argument of your success callback will be a JavaScript object containing many properties including a data property whose value is the parsed JavaScript object based on the JSON returned by your API. Trying to parse a JavaScript object will result in error.
Try modifying the success method to:
.success(function (response, status, headers, config) {
var myjson = response.data;
$scope.dtDioSearch = myjson;
});
Public Function GetJSon(ByVal dt As DataTable) As List(Of Dictionary(Of String, Object))
Dim rows As New List(Of Dictionary(Of String, Object))
Dim row As Dictionary(Of String, Object)
'Return JsonConvert.SerializeObject(dt).ToList
'Return JSONString
For Each dr As DataRow In dt.Rows
row = New Dictionary(Of String, Object)
For Each col As DataColumn In dt.Columns
If col.DataType = GetType(Date) Then
Dim dtt As DateTime = DateTime.Parse(dr(col).ToString())
row.Add(col.ColumnName, dtt.ToString("dd-MM-yyyy hh:mm:ss"))
Else
row.Add(col.ColumnName, dr(col))
End If
Next
rows.Add(row)
Next
Return rows
End Function
#tj thank you for your support. the problem is json return string and i changed it to array list

Fullcalendar in ASP.NET and JSON response

I am fetching my events with webservice:
Public Function webGetCalendarEvents(ByVal startDate As String, ByVal endDate As String) As String
Dim sDate As DateTime = ToUnixTimeSpan(startDate)
Dim eDate As DateTime = ToUnixTimeSpan(endDate)
Dim DS As DataSet = DBStoredProcedures.GetEventsCalendarJSON(95, sDate, eDate)
DS.Tables(0).TableName = "events"
Dim dataTable As DataTable = DS.Tables(0)
Dim jsonEvents As String = Newtonsoft.Json.JsonConvert.SerializeObject(dataTable)
Return jsonEvents
The json response is like:
[
{
"id":589311,
"title":"My Title",
"priority":"",
"start":"2011-09-19T08:00",
"end":"2011-09-26T16:00",
"allDay":"false",
"editable":"true",
"EOSid":0
}
]
The problem is, that all my events are shown as allDay events. It seems like "false" value of "allDay" is not recognized.
I am evaluating the response inside fullcalendar.js file (version 1.5.2., line around 981):
success: function (events) {
events = (typeof events.d) == 'string' ? eval('(' + events.d + ')') : events.d || [];
How can I render events to accept "allDay" parameter?
SOLVED:
I changed my SQL procedure where I was generating "allDay" parameter. I changed from:
CASE WHEN EventTypeID=3 THEN 'false' ELSE 'true' END as allDay
to:
CASE WHEN EventTypeID=3 THEN CAST(0 as BIT) ELSE CAST(1 as BIT) END as allDay
This gave me JSON response:
{"allDay": false}
instead of:
{"allDay": "false"}