vb.net datatable Serialize to json - json

I have this kind of table:
I need to get this JSON (of course order could be any, structure/tree is most important):
Data table can change, so serialization should be dynamic. I am working with vb.net and used this code:
Public Function GetJson() As String
Dim dt As New System.Data.DataTable
dt = CreateDataTable() 'here I retrive data from oracle DB
Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer()
Dim packet As New List(Of Dictionary(Of String, Object))()
Dim row As Dictionary(Of String, Object) = Nothing
For Each dr As DataRow In dt.Rows
row = New Dictionary(Of String, Object)()
For Each dc As DataColumn In dt.Columns
row.Add(dc.ColumnName.Trim(), dr(dc))
Next
packet.Add(row)
Next
Return serializer.Serialize(packet)
End Function
But this code returns me bad json: [{"NAME":"city","PARENT":"address","VALUE":"has child"},{"NAME":"coordinates","PARENT":"address","VALUE":"has child"},{"NAME":"street","PARENT":"address","VALUE":"has child"}.......
Can someone help me out in here?

The 'Oh-no you didn't' version:
Public Function GetJson(ByVal dt As DataTable) As String
Return New JavaScriptSerializer().Serialize(From dr As DataRow In dt.Rows Select dt.Columns.Cast(Of DataColumn)().ToDictionary(Function(col) col.ColumnName, Function(col) dr(col)))
End Function

Here is my solution:
Public Function GetJson() As String
Dim dt As New System.Data.DataTable
dt = CreateDataTable() 'here I retrive data from oracle DB
Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer()
Dim packet As New List(Of Dictionary(Of String, Object))()
Dim row As Dictionary(Of String, Object) = Nothing
Try
Dim result() As DataRow = dt.Select("Parent_ = 'main'")
Dim i As Integer
For i = 0 To result.GetUpperBound(0)
row = New Dictionary(Of String, Object)()
If UCase(result(i)(2)) <> "HAS CHILD" Then
row.Add(result(i)(0), result(i)(2))
Else
row.Add(result(i)(0), add_(dt, result(i)(0)))
End If
packet.Add(row)
Next i
Return serializer.Serialize(packet)
Catch ex As Exception
MsgBox(ex.ToString)
Me.Close()
End Try
End Function
Public Function add_(ByVal dt As System.Data.DataTable, ByVal parent_ As String) As Dictionary(Of String, Object)
Dim row As Dictionary(Of String, Object) = Nothing
Try
Dim result() As DataRow = dt.Select("Parent_ = '" & parent_ & "'")
Dim i As Integer
row = New Dictionary(Of String, Object)()
For i = 0 To result.GetUpperBound(0)
If UCase(result(i)(2)) <> "HAS CHILD" Then
row.Add(result(i)(0), result(i)(2))
Else
row.Add(result(i)(0), add_(dt, result(i)(0)))
End If
Next i
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Return row
End Function

Related

How can I handle parsed JSON property/value not existing in VB.Net?

I shall get to the point and it is probably an easy answer for someone. The JSON being returned from HubSpot may or may not include a property such as phone and address because it is not filled out in HubSpot. This causes an error in the For Each block below:
System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=HubSpotGetAllCompanies
How can I handle it so that if there is no property for telephone for example, I can put in a DBNull value instead.
Thanks in advance!
Imports System.ComponentModel
Imports System.IO
Imports System.Net
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Module Index
Sub Main()
Dim counter = 0
Dim offset As String = String.Empty
Dim hasmore As Boolean = False
Dim hapikey = "xxx"
Dim hubSpot As New Dal.HubSpot.Pull
'Create Table
Dim companiesTable As DataTable = New DataTable()
companiesTable.Columns.Add("PortalID")
companiesTable.Columns.Add("CompanyID")
companiesTable.Columns.Add("Company")
companiesTable.Columns.Add("Website")
companiesTable.Columns.Add("Address1")
companiesTable.Columns.Add("City")
companiesTable.Columns.Add("Country")
companiesTable.Columns.Add("Postcode")
companiesTable.Columns.Add("Telephone")
companiesTable.Columns.Add("Ref")
companiesTable.Columns.Add("VatCode")
'Create Values
'Loop as you can only return so many companies at once (250 is limit I believe)
Do
Dim url As String = String.Format("https://api.hubapi.com/companies/v2/companies/paged?hapikey={0}&properties=name&properties=website&properties=address&properties=city&properties=country&properties=zip&properties=phone&limit=10{1}", hapikey, offset)
Dim httpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
httpWebRequest.ContentType = "application/json"
httpWebRequest.Method = "GET"
Dim httpResponse = CType(httpWebRequest.GetResponse(), HttpWebResponse)
Using streamReader = New StreamReader(httpResponse.GetResponseStream())
Dim result = streamReader.ReadToEnd()
Dim jObject As JObject = JObject.Parse(result)
Dim jhasmore As JToken = jObject("has-more")
Dim joffset As JToken = jObject("offset")
Dim jcompanies As JToken = jObject("companies")
If jhasmore.ToString().ToLower() = "true" Then
hasmore = True
Else
hasmore = False
End If
offset = String.Format("&offset={0}", joffset.ToString())
For Each item In jcompanies.ToList()
Dim portalId = item("portalId").ToString()
Dim companyId = item("companyId").ToString()
Dim company = item("properties")("name")("value").ToString()
Dim website = If(item("properties")("website")("value").ToString(), DBNull.Value)
Dim address1 = If(item("properties")("address")("value").ToString(), DBNull.Value)
Dim city = If(item("properties")("city")("value").ToString(), DBNull.Value)
Dim country = If(item("properties")("country")("value").ToString(), DBNull.Value)
Dim postcode = If(item("properties")("zip")("value").ToString(), DBNull.Value)
Dim telephone = If(item("properties")("phone")("value").ToString(), DBNull.Value)
Dim ref = DBNull.Value
Dim vatCode = DBNull.Value
companiesTable.Rows.Add(portalId, companyId, company, website, address1, city, country, postcode, telephone, ref, vatCode)
Next
End Using
counter += 1
Loop While hasmore
hubSpot.GetAllHubSpotCompanies(companiesTable)
End Sub
Try using the Null Propagation Operator ? between any token accessors that may not be filled:
Dim telephone = If(item("properties")("phone")?("value").ToString(), DBNull.Value)
If a particular token is Nothing, it will return Nothing to the If and set the variable to DBNull.Value

I am always getting fingerprint not verified

Anytime I scan a fingerprint for verification I get the message "Fingerprint not verified" even though I have already enrolled that fingerprint into the database. Here is the code for capture when the form loads
Here is the code for capture when the form loads
Private Sub Me_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Init()
StartCapture()
Dim conn As New MySqlConnection
Dim cmd As New MySqlCommand
Dim sql As String
conn.ConnectionString = "**** "
conn.Open()
sql = ("SELECT * FROM new_case_file")
cmd.Connection = conn
cmd.CommandText = sql
Dim rdr As MySqlDataReader = cmd.ExecuteReader()
While (rdr.Read())
Dim MemStream As IO.MemoryStream
Dim fpBytes As Byte()
fpBytes = rdr("FingerPrint")
MemStream = New IO.MemoryStream(fpBytes)
Dim templa8 As DPFP.Template = New DPFP.Template()
templa8.DeSerialize(MemStream)
Dim serializedTemplate As Byte() = MemStream.ToArray
Dim tmpObj As New AppData
Dim FPList As List(Of AppData) = New List(Of AppData)
'tmpObj.No = rdr("No").ToString()
'tmpObj.Template = templa8
'FPList.Add(tmpObj)
End While
conn.Close()
End Sub
Here is the code for verification. When l click on the button it should verify, because l called the sub verifyControl_Commplete in the button click sub.
Private Sub verifyControl_OnComplete(ByVal Control As Object, ByVal FeatureSet As DPFP.FeatureSet, ByRef EventHandlerStatus As
DPFP.Gui.EventHandlerStatus) Handles verifyControl.OnComplete
Dim printFound As Boolean = False
'Dim printFound As Boolean = True
'Dim printFound As Boolean = False
Dim VerifiedFPData = New AppData
Dim FPList As List(Of AppData) = New List(Of AppData)
Try
For Each FPData As AppData In FPList
Dim tmplateData As New DPFP.Template
'tmplateData = FPData.Template
Dim compareTo As New DPFP.FeatureSet
compareTo = FeatureSet
Dim ver As New DPFP.Verification.Verification()
Dim res As New DPFP.Verification.Verification.Result()
If Not tmplateData Is Nothing Then
ver.Verify(FeatureSet, tmplateData, res)
If res.Verified Then
EventHandlerStatus = DPFP.Gui.EventHandlerStatus.Success
printFound = True
VerifiedFPData = FPData
Exit For
End If
End If
Next
Catch ex As Exception
MessageBox.Show("Error")
End Try
If printFound Then
MsgBox("Verified")
Else
EventHandlerStatus = DPFP.Gui.EventHandlerStatus.Failure
MsgBox("Not Verified")
End If
End Sub
Private Sub btnverifyfp_Click(sender As Object, e As EventArgs) Handles btnverifyfp.Click
verifyControl_OnComplete(Nothing, Nothing, Nothing)
End Sub
This is the code l used in saving the fingerprint
Dim fingerprintData As MemoryStream = New MemoryStream
Enroller.Template.Serialize(fingerprintData)
Dim serializedTemplate As Byte() = fingerprintData.ToArray()
Dim bytes() As Byte = serializedTemplate
Try this:
'THIS NEEDS TO BE AT THE CLASS-LEVEL, AS A MEMBER
Private FPList As New List(Of AppData)
Private Sub Me_Load(ByVal sender As System.Object, ByVal e AsSystem.EventArgs)
Handles MyBase.Load
Init()
StartCapture()
Dim sql As String = "SELECT * FROM new_case_file"
Using conn As New MySqlConnection("**** "), _
cmd As New MySqlCommand(sql, conn)
conn.Open()
Using rdr As MySqlDataReader = cmd.ExecuteReader()
FPList.Clear()
While (rdr.Read())
Dim tmpObj As New AppData
tmpObj.No = rdr("No").ToString()
Dim fpBytes As Byte() = rdr("FingerPrint")
Using MemStream As New IO.MemoryStream(fpBytes)
Dim templa8 As New DPFP.Template()
templa8.DeSerialize(MemStream)
End Using
tmpObj.Template = templa8
FPList.Add(tmpObj)
End While
rdr.Close()
End Using
End Using
End Sub
And now other code later can use that same FPList variable. If you find yourself writing New List(Of AppData) anywhere else, you're doing something wrong.
The AppData class should look something like this:
Public Class AppData
Public Property No As String
Public Property Template As DFFP.Template
End Class
And finally, the verify code:
Private Sub verifyControl_OnComplete(ByVal Control As Object, ByVal FeatureSet As DPFP.FeatureSet,
ByRef EventHandlerStatus As DPFP.Gui.EventHandlerStatus)
Handles verifyControl.OnComplete
Try
Dim ver As New DPFP.Verification.Verification()
Dim res As New DPFP.Verification.Verification.Result()
For Each FPData As AppData In FPList
If FPData.Template Is Nothing Then Continue
ver.Verify(FeatureSet, FPData.Template, res)
If res.Verified Then
EventHandlerStatus = DPFP.Gui.EventHandlerStatus.Success
MsgBox("Verified")
Return
End If
Next FPDAta
Catch ex As Exception
MessageBox.Show("Error")
End Try
EventHandlerStatus = DPFP.Gui.EventHandlerStatus.Failure
MsgBox("Not Verified")
End Sub
Again... we don't have access to your API documentation, test data, or equipment. That means we're blind trying to help you here. There's probably some things wrong with this, and you'll have to be able to troubleshoot and debug.

how to parse json in vb.net

I have json: {'success':'1','return':[{'id':'32928888','datetime':'2014-03-25 02:49:21','price':'0.02800939','quantity':'0.26094649','total':'0.00730895','io':'Buy'},{'id':'32928884','datetime':'2014-03-25 02:49:18','price':'0.02800939','quantity':'0.09930853','total':'0.00278157','io':'Buy'},{'id':'32928850','datetime':'2014-03-25 02:48:49','price':'0.02800939','quantity':'0.00093585','total':'0.00002621','io':'Buy'},{'id':'32928848','datetime':'2014-03-25 02:48:48','price':'0.02800939','quantity':'0.23547262','total':'0.00659544','io':'Sell'},{'id':'32928698','datetime':'2014-03-25 02:47:42','price':'0.02800939','quantity':'0.25553470','total':'0.00715737','io':'Sell'},{'id':'32928540','datetime':'2014-03-25 02:47:05','price':'0.02800940','quantity':'0.00820048','total':'0.00022969','io':'Sell'}]}
and I use code:
Public Function parse_json(ByVal json As String) As Nullable
Try
Dim jResults As JObject = JObject.Parse(json)
Dim results As List(Of JToken) = jResults.Children().ToList()
For Each item As JProperty In results
item.CreateReader()
MsgBox(item.Value("id"))
MsgBox(item.Value("datetime"))
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Function
But I get error saying: System.InvalidOperationException: Cannot access child value on Newtonsoft.Json.Linq.JValue. What am I doing wrong? I need to get all ids, prices and so on.
return is the child of the full object:
Dim results As JArray = jResults.GetValue("return");
I changed the codes which is tested working as:
Public Function parse_json(ByVal json As String) As Nullable
Try
Dim jResults As JObject = JObject.Parse(json)
' Dim results As List(Of JToken) = jResults.Children().ToList()
Dim arrResult As JArray = jResults.GetValue("return")
For Each item As JObject In arrResult
'item.CreateReader()
'MsgBox(item.Value("id"))
'MsgBox(item.Value("datetime"))
Dim strid As String = item.GetValue("id")
Dim strdt As String = item.GetValue("datetime")
Diagnostics.Debug.WriteLine("id: " & strid)
Diagnostics.Debug.WriteLine("dt: " & strdt)
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Function

asmx won't return JSON

I've completely rewritten this old asmx service function but I still can't get it to return JSON. It returns XML, even if I use ajax() and set the datatype and contenttype to json. I'm trying to use this function with Jquery dataTables. And I know there are tons of questions like this but all of them I've found are C# and I was unable to adapt them.
up-to-date pastebin of full asmx file: http://pastebin.com/swXKqgd4
new code
<WebMethod()> _
<WebGet(ResponseFormat:=WebMessageFormat.Json)> _
Public Function rptPendingServerRequests() As Generic.List(Of request)
Dim _conn As SqlConnection = New SqlConnection(connectionString)
Dim _dr As SqlDataReader
Dim Sql As String = String.Empty
Sql += "<My query here>"
Try
Dim _cmd As SqlCommand = New SqlCommand(Sql, _conn)
_conn.Open()
_dr = _cmd.ExecuteReader(CommandBehavior.CloseConnection)
If _dr.HasRows Then
Dim s As request
Dim c As New Generic.List(Of request)
While _dr.Read
s = New request
With s
.requestID = _dr("request_id")
.status = _dr("status")
.requester = _dr("req_by_user_id")
.assignee = _dr("user_id")
.nextAction = _dr("description")
End With
c.Add(s)
End While
Return c
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
_conn.Close()
End Try
End Function
New class
<Serializable()> _
Public Class request
Private _requestID As Integer
Public Property requestID() As Integer
Get
Return _requestID
End Get
Set(ByVal value As Integer)
_requestID = value
End Set
End Property
Private _requester As String
Public Property requester() As String
Get
Return _requester
End Get
Set(ByVal value As String)
_requester = value
End Set
End Property
Private _requestDate As Date
Public Property requestDate() As Date
Get
Return _requestDate
End Get
Set(ByVal value As Date)
_requestDate = value
End Set
End Property
Private _status As Integer
Public Property status() As Integer
Get
Return _status
End Get
Set(ByVal value As Integer)
_status = value
End Set
End Property
Private _assignee As String
Public Property assignee() As String
Get
Return _assignee
End Get
Set(ByVal value As String)
_assignee = value
End Set
End Property
Private _nextAction As String
Public Property nextAction() As String
Get
Return _nextAction
End Get
Set(ByVal value As String)
_nextAction = value
End Set
End Property
End Class
Original Code
<WebMethod()> _
<WebGet(ResponseFormat:=WebMessageFormat.Json)> _
Public Function rptPendingServerRequestsOld() As DataSet
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
sql = ""
sql += "<MY query here>"
connection = New SqlConnection(connectionString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds)
adapter.Dispose()
command.Dispose()
connection.Close()
Return ds
Catch ex As Exception
End Try
End Function
Client
$('#report').dataTable({
"bProcessing": true,
"sAjaxSource": 'reportdata.asmx/rptPendingServerRequests'
});
Since you're calling this method from JS instead of
<WebGet(ResponseFormat:=WebMessageFormat.Json)>
use
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
attribute. Also don't forget to mark your WebService class with
<ScriptService()>
attribute.
Change this line.
Public Function rptPendingServerRequests() As Generic.List(Of request)
to
Public Function rptPendingServerRequests() As String.

Telerik Dock is duplicating boxes and "_breaking_" the webpage, how can I fix the problem?

Here is the Code:
VB:
Imports System.Web.Script.Serialization
Partial Class MyLanding
Inherits System.Web.UI.Page
Private LoginClass As New LoginClass
Private _dockStateCleared As Boolean = False
Private _conn As New SqlConnection(ConfigurationManager.ConnectionStrings("MidwestPartsConnectionString").ConnectionString)
Private ReadOnly Property CurrentDockStates() As List(Of DockState)
Get
'Get saved state string from the database - set it to dockState variable for example
Dim dockStatesFromDB As String = ""
_conn.Open()
Dim command As New SqlCommand("SELECT JavascriptStr FROM SysProperties WHERE (UserID = #UserID)", _conn)
command.Parameters.Add("#UserID", SqlDbType.UniqueIdentifier).Value = Me.LoginClass.ReturnUserID()
Try
dockStatesFromDB = command.ExecuteScalar().ToString()
_conn.Close()
Catch ex As Exception
_conn.Close()
Me.CreateSavedLayout("")
End Try
Dim _currentDockStates As New List(Of DockState)()
Dim stringStates As String() = dockStatesFromDB.Split("|"c)
For Each stringState As String In stringStates
If stringState.Trim() <> String.Empty Then
_currentDockStates.Add(DockState.Deserialize(stringState))
End If
Next
Return _currentDockStates
End Get
End Property
Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
If Not Page.IsPostBack Then
If CurrentDockStates.Count = 0 Then
Me.LoadItems()
End If
End If
End Sub
Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Init
Dim i As Integer = 0
While i < CurrentDockStates.Count
If CurrentDockStates(i).Closed = False Then
Dim dock As RadDock = CreateRadDockFromState(CurrentDockStates(i))
dlColumnOne.Controls.Add(dock)
CreateSaveStateTrigger(dock)
LoadUserControl(dock)
End If
System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
End While
End Sub
Protected Sub dlColumnOne_LoadDockLayout(ByVal sender As Object, ByVal e As DockLayoutEventArgs)
For Each state As DockState In CurrentDockStates
e.Positions(state.UniqueName) = state.DockZoneID
e.Indices(state.UniqueName) = state.Index
Next
End Sub
Protected Sub dlColumnOne_SaveDockLayout(ByVal sender As Object, ByVal e As DockLayoutEventArgs)
Dim stateList As List(Of DockState) = dlColumnOne.GetRegisteredDocksState()
Dim serializedList As New StringBuilder()
Dim i As Integer = 0
While i < stateList.Count
serializedList.Append(stateList(i).ToString())
serializedList.Append("|")
System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
End While
Dim dockState As String = serializedList.ToString()
If dockState.Trim() <> [String].Empty Then
_conn.Open()
Dim command As New SqlCommand([String].Format("update sysproperties set javascriptstr = '{0}' Where UserID = #UserID ", dockState), _conn)
command.Parameters.Add("#UserID", SqlDbType.UniqueIdentifier).Value = Me.LoginClass.ReturnUserID()
command.ExecuteNonQuery()
_conn.Close()
End If
End Sub
Private Function CreateRadDockFromState(ByVal state As DockState) As RadDock
Dim dock As New RadDock()
dock.DockMode = DockMode.Docked
dock.UniqueName = state.UniqueName
dock.ID = String.Format("RadDock{0}", dock.UniqueName)
dock.ApplyState(state)
dock.Commands.Add(New DockCloseCommand())
dock.Commands.Add(New DockExpandCollapseCommand())
Return dock
End Function
Private Function CreateRadDock(ByVal DockTitle As String) As RadDock
Dim docksCount As Integer = CurrentDockStates.Count
Dim dock As New RadDock
dock.DockMode = DockMode.Docked
Dim UniqueName As String = Guid.NewGuid().ToString()
UniqueName = UniqueName.Replace("-", "")
dock.UniqueName = UniqueName
dock.ID = String.Format("RadDock{0}", UniqueName)
dock.Title = DockTitle
dock.Width = Unit.Pixel(400)
dock.Commands.Add(New DockCloseCommand())
dock.Commands.Add(New DockExpandCollapseCommand())
Return dock
End Function
Private Sub LoadItems()
Dim DocksDataTable As DataTable = Me.ReturnReports()
For i = 0 To DocksDataTable.Rows.Count() - 1
Dim dock As RadDock = Me.CreateRadDock(DocksDataTable.Rows(i).Item("ReportTitle").ToString())
Dim dz As RadDockZone = Me.dzColumnOne
Dim dl As RadDockLayout = Me.dlColumnOne
dz.Controls.Add(dock)
Me.CreateSaveStateTrigger(dock)
dock.Tag = DocksDataTable.Rows(i).Item("ReportPath")
Me.LoadUserControl(dock)
Next
End Sub
Public Function ReturnReports() As DataTable
Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("MidwestPartsConnectionString").ConnectionString)
Dim Query As String = "SELECT Reports.ReportPath, Reports.ReportTitle, UserReports.UserID FROM UserReports INNER JOIN Reports ON UserReports.ReportID = Reports.ReportID WHERE (UserReports.UserID = #UserID)"
Dim adapter As New SqlDataAdapter
adapter.SelectCommand = New SqlCommand(Query, connection)
adapter.SelectCommand.Parameters.Add("#UserID", SqlDbType.UniqueIdentifier).Value = Me.LoginClass.ReturnUserID()
Dim table1 As New DataTable
connection.Open()
Try
adapter.Fill(table1)
Finally
connection.Close()
End Try
Return table1
End Function
Private Function ReturnLayout() As DataTable
Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("MidwestPartsConnectionString").ConnectionString)
Dim Query As String = "select * from sysproperties"
Dim adapter As New SqlDataAdapter
adapter.SelectCommand = New SqlCommand(Query, connection)
adapter.SelectCommand.Parameters.Add("#UserPropertiesID", SqlDbType.Int).Value = 1
Dim table1 As New DataTable
connection.Open()
Try
adapter.Fill(table1)
Finally
connection.Close()
End Try
Return table1
End Function
Private Sub LoadUserControl(ByVal dock As RadDock)
If String.IsNullOrEmpty(dock.Tag) Then
Return
End If
Dim usercontrol As Control = LoadControl(dock.Tag)
dock.ContentContainer.Controls.Add(usercontrol)
End Sub
Private Sub CreateSaveStateTrigger(ByVal dock As RadDock)
dock.AutoPostBack = True
dock.CommandsAutoPostBack = True
Dim saveStateTrigger As New AsyncPostBackTrigger()
saveStateTrigger.ControlID = dock.ID
saveStateTrigger.EventName = "DockPositionChanged"
UpdatePanel1.Triggers.Add(saveStateTrigger)
saveStateTrigger = New AsyncPostBackTrigger()
saveStateTrigger.ControlID = dock.ID
saveStateTrigger.EventName = "Command"
UpdatePanel1.Triggers.Add(saveStateTrigger)
End Sub
Private Sub CreateSavedLayout(ByVal JavascriptStr As String)
Dim sqlConn As New SqlConnection(ConfigurationManager.ConnectionStrings("MidwestPartsConnectionString").ConnectionString)
Dim strSqlInsert As String = "INSERT INTO SysProperties(UserID, JavascriptStr) VALUES (#UserID, #JavascriptStr)"
strSqlInsert += "; SELECT SCOPE_IDENTITY() ;"
Dim sqlCmd As New SqlCommand(strSqlInsert, sqlConn)
With sqlCmd.Parameters
.Add("#JavascriptStr", SqlDbType.Text).Value = JavascriptStr
.Add("#UserID", SqlDbType.UniqueIdentifier).Value = Me.LoginClass.ReturnUserID()
End With
sqlCmd.Connection.Open()
sqlCmd.ExecuteScalar()
sqlCmd.Connection.Close()
End Sub
Protected Sub btnAddReports_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddReports.Click
Try
Response.Redirect("~/MyUserAccount/SelectedReports.aspx", False)
Catch ex As Exception
End Try
End Sub
End Class
Your could looks fine. Possible reasons for this problem include the following:
Dragging the Dock control very quickly causes an ajax conflict, and an error is shown. To avoid this from happening you could show an AjaxLoading panel during the process of an ajax request (search/ask in the telerik forums for a sample showing how to do this). Additionally you should make sure the UpdatePanels on your site are configured as in the following online demo: http://demos.telerik.com/aspnet-ajax/dock/examples/myportal/defaultcs.aspx.
The error is a result of a ViewState problem. This telerik forum thread provides a possible solution: www.telerik.com/community/forums/aspnet-ajax/docking/failed-to-load-view-state-error-when-moving-dynamically-created-widgets-around-the-raddocklayout.aspx