Calling and serializing FB feed - asp.net

I am calling FB feed from multiple FB pages with
/posts?ids=OI.Plavipingvin,217384491624554&limit=5&fields=message,created_time,id
This is the feed I get:
{
"217384491624554": {
"data": [
{
"message": "Obećanje i zavjet položeni. Dobrodošli u OI Javor ❤",
"created_time": "2017-01-08T01:05:25+0000",
"id": "217384491624554_1575515795811410"
},
{
"message": "Zimovanje u punom tijeku :-)",
"created_time": "2017-01-04T10:06:57+0000",
"id": "217384491624554_1572127976150192"
}
],
"paging": {
"previous": "https://graph.facebook.com/v2.8/217384491624554/posts?fields=message,created_time,id&limit=2&format=json&since=1483837525&access_token=EAACEdEose0cBAMlhIYetCMo0m83Jdo3F7rk4NYmm47Q1T19UDxlKhMQnjDW4Mmelqu3vzTITnVA7E0ZBgl6jDmlHC8J7ZCX4TW2xB0xoHIySu3MK5d9yUWjqMLdUrRab9KTfH1WyzpEfIbxG7JlhPnZACfiFWFfhvO9vrAZCrAZDZD&__paging_token=enc_AdB6GEshkXkXuRJcuiHCF1aoS4rK7Myp3P6mFZAUFeZAPbRVdtmihE7UAOIlFDuTjVKHvmBeiMLmWfIZBfCER7cYrS08kccUDDoixEb2ZABASuwAigZDZD&__previous=1",
"next": "https://graph.facebook.com/v2.8/217384491624554/posts?fields=message,created_time,id&limit=2&format=json&access_token=EAACEdEose0cBAMlhIYetCMo0m83Jdo3F7rk4NYmm47Q1T19UDxlKhMQnjDW4Mmelqu3vzTITnVA7E0ZBgl6jDmlHC8J7ZCX4TW2xB0xoHIySu3MK5d9yUWjqMLdUrRab9KTfH1WyzpEfIbxG7JlhPnZACfiFWFfhvO9vrAZCrAZDZD&until=1483524417&__paging_token=enc_AdBeiIQZBem7NbobO8r183HtpPnZAOY6CRyehrr8uDJZBXkSS5kKS3YpqdmosFZCGZBobXwMnKW4hEsAIEZCjhYCAL2NdAX7ZCZAyWHZB7GhQCS0IQIqEZBwZDZD"
}
},
"OI.Plavipingvin": {
"data": [
{
"message": "Sretnu novu godinu želi vam Uprava odreda. Budite sretni i zadovoljni. I naravno - pripravni za nove avanture! 🎈 🎈 🎈",
"created_time": "2017-01-02T10:07:27+0000",
"id": "379925365427474_1274199672666701"
},
{
"message": "Jutros na Omanovcu. Imamo snijeg! :)",
"created_time": "2016-12-28T07:03:07+0000",
"id": "379925365427474_1269358063150862"
}
],
"paging": {
"previous": "https://graph.facebook.com/v2.8/379925365427474/posts?fields=message,created_time,id&limit=2&format=json&since=1483351647&access_token=EAACEdEose0cBAMlhIYetCMo0m83Jdo3F7rk4NYmm47Q1T19UDxlKhMQnjDW4Mmelqu3vzTITnVA7E0ZBgl6jDmlHC8J7ZCX4TW2xB0xoHIySu3MK5d9yUWjqMLdUrRab9KTfH1WyzpEfIbxG7JlhPnZACfiFWFfhvO9vrAZCrAZDZD&__paging_token=enc_AdDjsccg8E9vHw7XXgXW22NDK0l3MH4mR5XvwXidebNK2Kb8bdewjPiTLGDP8yNw8rpcHYT8VME5YPxLhZC0QZCjdLkHBYJCQZBYdQQWsfmhmC2yQZDZD&__previous=1",
"next": "https://graph.facebook.com/v2.8/379925365427474/posts?fields=message,created_time,id&limit=2&format=json&access_token=EAACEdEose0cBAMlhIYetCMo0m83Jdo3F7rk4NYmm47Q1T19UDxlKhMQnjDW4Mmelqu3vzTITnVA7E0ZBgl6jDmlHC8J7ZCX4TW2xB0xoHIySu3MK5d9yUWjqMLdUrRab9KTfH1WyzpEfIbxG7JlhPnZACfiFWFfhvO9vrAZCrAZDZD&until=1482908587&__paging_token=enc_AdDZCnhwlRCxibv0aGr141JPdbcHcJssKFjhtToaTpfqKbZABvo5g0fhtCgDpwCNoMBopGK4o0CJxXzRyRJKxLCqOh0belZCXBQdTNZCEF5eRuu6agZDZD"
}
}
}
My current FBClass:
Public Class FBData
Public Property data As New List(Of FBFeed)
End Class
Public Class FBFeed
Public Property message As String
Public Property created_time As DateTime
Public Property id As String
End Class
Current GetPosts function, ordering and showing result:
Public Shared Function GetPosts( accessToken As String ) As FBData
Dim APIlink As String = "https://graph.facebook.com/posts?ids=OI.Plavipingvin,217384491624554&limit=5&fields=message,created_time,id&access_token=" & accessToken
Dim client As New WebClient()
client.Encoding = System.Text.Encoding.UTF8
Dim strJson As [String] = client.DownloadString(APIlink)
Dim result As FBData = Newtonsoft.Json.JsonConvert.DeserializeObject(Of FBData)( strJson )
Return result
End Function
Dim array1 As FBData = GetPosts ( accessToken )
For Each Msg As FBFeed In array1.data.OrderByDescending(Function(x) x.created_time)
Response.Write( i & ". " & Msg.created_time & "<br />" )
Next
What FBClass should I use for serialization of this JSON and how to read FBClass list (or array)? I don't need User-ID or data tags.

While my other answer works, it's a bit clumsy if one has a bunch of feeds to deal with, so this should be a more effective answer. I chose not to edit the previous answer because it's valid depending on one's needs.
Given this revised class structure...
Public Class FBFeed
Public Property data As Datum()
Public Property paging As Paging
End Class
Public Class Datum
Public Property message As String
Public Property created_time As DateTime
Public Property id As String
End Class
Public Class Paging
Public Property previous As String
Public Property [next] As String
End Class
...and this revised GetPosts method...
Public Shared Function GetPosts(accessToken As String, ParamArray args() As String) As Dictionary(Of String, FBFeed)
'Dim APIlink As String = "https://graph.facebook.com/posts?ids=OI.Plavipingvin,217384491624554&limit=5&fields=message,created_time,id&access_token=" & accessToken
Dim Ids As String = Join(args, ",")
Dim APITemplate As String = "https://graph.facebook.com/posts?ids={0}&limit=5&fields=message,created_time,id&access_token={1}"
Dim APIlink As String = String.Format(APITemplate, Ids, accessToken)
Using client As New WebClient()
client.Encoding = Text.Encoding.UTF8
Dim strJson As String = client.DownloadString(APIlink)
Return Newtonsoft.Json.JsonConvert.DeserializeObject(Of Dictionary(Of String, FBFeed))(strJson)
End Using
End Function
...the usage in the page request handler becomes...
Dim MyData As New List(Of Datum)
Dim IdList As New List(Of String)
IdList.Add("OI.Plavipingvin")
IdList.Add("217384491624554")
With GetPosts("Access Token Here", IdList.ToArray)
' We have a Dictionary(Of String, FBFeed) we can flatten with SelectMany
' and consolidate the Datum arrays into the MyData List(Of Datum) above
MyData.AddRange(.Values.SelectMany(Function(x) x.data).ToList())
End With
For Each Msg As Datum In MyData.OrderByDescending(Function(x) x.created_time)
Response.Write(Msg.message & ". " & Msg.created_time & "<br />")
Next

The class structure would have to look like this:
Imports Newtonsoft.Json
Public Class FBData
<JsonProperty(PropertyName:="217384491624554")>
Public Property Feed_217384491624554 As FBFeed
<JsonProperty(PropertyName:="OI.Plavipingvin")>
Public Property Feed_OIPlavipingvin As FBFeed
End Class
Public Class FBFeed
Public Property data As Datum()
Public Property paging As Paging
End Class
Public Class Datum
Public Property message As String
Public Property created_time As DateTime
Public Property id As String
End Class
Public Class Paging
Public Property previous As String
Public Property [next] As String
End Class
Update: Usage:
Dim array1 As FBData = GetPosts ( accessToken )
Dim MyData As New List(Of Datum)
MyData.AddRange(array1.Feed_217384491624554.data)
MyData.AddRange(array1.Feed_OIPlavipingvin.data)
For Each Msg As Datum In MyData.OrderByDescending(Function(x) x.created_time)
Response.Write(Msg.message & ". " & Msg.created_time & "<br />")
Next

Related

Serialise list of objects to single JSON object, with property as key:value

Public Class Doc
Public TypeDoc As String = ""
Public Property UserFields As New List(Of UserField)
End Class
Public Class UserField
Property Name As String = ""
Property Value As String = ""
End Class
Public Class Example
Public Sub test()
Dim d As New Doc
d.TypeDoc = "Order"
d.UserFields.Add(New UserField With {.Name = "U_Name", .Value = "Jonny"})
d.UserFields.Add(New UserField With {.Name = "U_Surname", .Value = "Goodman"})
Dim Ret As String = JsonConvert.SerializeObject(d)
End Sub
End Class
Desired result "Ret":
{
"TypeDoc": "Order",
"U_Name": "Jonny",
"U_Surname": "Goodman",
}
I hope you understand the example, I was wondering if it was possible to have this result.
Thank you

ArrayList from Class with Reflection

I need to use Reflection for this problem.
Just a simple code needed written in ASP.net and reflection.
Reflection is a must.
Please take a look attached file for more info and example.
I just want to make the code below working. Output does not work as expected! Shows the same result!
Public Class JoinTables
Public Class userz_N_user_roles
Public userz As New userz
Public user_roles As New user_roles
End Class
End Class
Public Class userz
Public Shared id As Nullable(Of Integer) = Nothing
Public user_name As String
Public email_email As String
Public user_pass As String
End Class
Public Class user_roles
Public id As Nullable(Of Integer) = Nothing
Public role_name As String
End Class
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim ArrayList_users As New ArrayList
Dim MyUser1 As New userz
myuser1.email_email = "1#test.com"
myuser1.user_name = "myuser1"
myuser1.user_pass = "mypass1"
ArrayList_users.Add(MyUser1)
Dim ArrayList_roles As New ArrayList
Dim MyUserRoles1 As New user_roles
MyUserRoles1.id = "1"
MyUserRoles1.role_name = "Admin"
ArrayList_roles.Add(MyUserRoles1)
Dim myuser2 As New userz
myuser2.email_email = "2#test.com"
myuser2.user_name = "myuser2"
myuser2.user_pass = "mypass2"
ArrayList_users.Add(myuser2)
Dim MyUserRoles2 As New user_roles
MyUserRoles2.id = "1"
MyUserRoles2.role_name = "Admin"
ArrayList_roles.Add(MyUserRoles2)
'############ REFLECTION PART ###############
Dim MyArrayList As New ArrayList 'for Response
Dim MyJoinTableClass As New JoinTables.userz_N_user_roles
Dim t As Type = MyJoinTableClass.GetType
t.InvokeMember("userz", BindingFlags.SetField, Nothing, MyJoinTableClass, New Object() {MyUser1})
t.InvokeMember("user_roles", BindingFlags.SetField, Nothing, MyJoinTableClass, New Object() {MyUserRoles1})
'MsgBox(MyUser1.user_name)
MyArrayList.Add(MyJoinTableClass)
Dim MyJoinTableClass2 As New JoinTables.userz_N_user_roles
t = MyJoinTableClass2.GetType
t.InvokeMember("userz", BindingFlags.SetField, Nothing, MyJoinTableClass, New Object() {myuser2})
t.InvokeMember("user_roles", BindingFlags.SetField, Nothing, MyJoinTableClass, New Object() {MyUserRoles2})
MyArrayList.Add(MyJoinTableClass)
Dim filledJoinCls1 As New JoinTables.userz_N_user_roles
filledJoinCls1 = MyArrayList(0)
Dim filledJoinCls1_user1 As New userz
filledJoinCls1_user1 = filledJoinCls1.userz
MsgBox(filledJoinCls1_user1.user_name)
Dim filledJoinCls2 As New JoinTables.userz_N_user_roles
filledJoinCls2 = MyArrayList(1)
Dim filledJoinCls2_user2 As New userz
filledJoinCls2_user2 = filledJoinCls2.userz
MsgBox(filledJoinCls1_user1.user_name & " - " & filledJoinCls2_user2.user_name)
End Sub
Output does not work as expected! Shows the same result!
See below,
public class Employee
{
private long emplNbr;
private string name;
public long EmployeeNumber
{
get { return emplNbr; }
set { emplNbr = value; }
}
public string EmployeeName
{
get { return name; }
set { name = value; }
}
}
Creating an Array of Objects
Employee[] StaffMembers = new Employee[2];
Initializing an Array of Objects
StaffMembers[0] = new Employee();
StaffMembers[0].EmployeeNumber = 20204;
StaffMembers[0].EmployeeName = "Harry Fields";
StaffMembers[1] = new Employee();
StaffMembers[1].EmployeeNumber = 92857;
StaffMembers[1].EmployeeName = "Jennifer Almonds";

ASP.NET Web Pages (Razor) Exit Code Block

Does anybody know how to exit a code block without interrupting page load in ASP.NET Web Page (Razor) in VB language? Let's say I have a login mechanism that execute in the following order:
Before page load:
Check if user id exist.
Check if password match.
if the user id does not exist, display error message then skip password validation and let the rest of the html page (body, footer) load. My current solution is to use VB specific GoTo.. statement which I think is ugly. Does anybody has a more elegant solution? Below is a simple sample code:
#Code
dim login As New clsLogin 'assume this class handles login validation
dim inputUserID As String 'this variable hold user id entered by user
dim inputPwd As String 'this is password entered by user
'First, check if that ID exist in database
if login.userExist(inputUserID) = false then
#<p>User does not exist !</p>
GoTo skip
End If
'If ID exist, check if password match
if login.checkPwd(inputUserID, inputPwd) = false then
#<p>Password Mismatch !</p>
GoTo skip
End If
'Passes all validation, display success message
#<p>Login Successful !</p>
skip:
End Code
I tried to replace the GoTo statement with return statement. However, it also stopped the page loading. I put the validation server code before any HTML is displayed and if I use return statement it wont show the HTML page. Any idea? Thanks in advance.
Short answer could use a function:
#Functions
function Check(byval inputUserID as integer, byval inputPwd as string) as string
dim login As New clsLogin 'assume this class handles login validation
dim result as string = string.Empty
'First, check if that ID exist in database
if login.userExist(inputUserID) = false then
return "User does not exist !"
End If
'If ID exist, check if password match
if login.checkPwd(inputUserID, inputPwd) = false then
return "Password Mismatch !"
End If
return result
end function
End functions
#Code
dim inputUserID As String 'this variable hold user id entered by user
dim inputPwd As String 'this is password entered by user
dim msg = #Check(inputUserID,inputPwd)
'Passes all validation, display success message
if string.isnullorempty(msg) then
msg = "<p>Login Successful !</p>"
end if
#msg
End Code
Hoever reading your comment seems you are looking for an elegant and sustainable solution, so I think you could approach your problem with a loosely coupled ValidationManager:
VB (translated with Telerik code converted)
Public Interface ILoginProvider
Function UserExist(inputUserID As Integer) As Boolean
Function CheckPwd(inputUserID As Integer, inputPwd As String) As Boolean
End Interface
Public Class LoginProvider
Implements ILoginProvider
Public Function UserExist(inputUserID As Integer) As Boolean
Return True
End Function
Public Function CheckPwd(inputUserID As Integer, inputPwd As String) As Boolean
Return True
End Function
End Class
Public Class ValidationResult
Public Property Result() As Boolean
Get
Return m_Result
End Get
Set
m_Result = Value
End Set
End Property
Private m_Result As Boolean
Public Property ResultMessage() As String
Get
Return m_ResultMessage
End Get
Set
m_ResultMessage = Value
End Set
End Property
Private m_ResultMessage As String
End Class
Public MustInherit Class Validator
Protected _provider As ILoginProvider
Protected _inputUserID As Integer
Protected _inputPwd As String
Public Sub New(provider As ILoginProvider, inputUserID As Integer, inputPwd As String)
_provider = provider
_inputPwd = inputPwd
_inputUserID = inputUserID
End Sub
Public MustOverride Function Validate() As ValidationResult
End Class
Public Class UserExistenceValidator
Inherits Validator
Public Sub New(provider As LoginProvider, inputUserID As Integer, inputPwd As String)
MyBase.New(provider, inputUserID, inputPwd)
End Sub
Public Overrides Function Validate() As ValidationResult
Dim result = New ValidationResult()
Dim check = _provider.UserExist(_inputUserID)
result.Result = check
If Not check Then
result.ResultMessage = "User Doesn't exist"
End If
Return result
End Function
End Class
Public Class UserPasswordValidator
Inherits Validator
Public Sub New(provider As LoginProvider, inputUserID As Integer, inputPwd As String)
MyBase.New(provider, inputUserID, inputPwd)
End Sub
Public Overrides Function Validate() As ValidationResult
Dim result = New ValidationResult()
Dim check = _provider.CheckPwd(_inputUserID, _inputPwd)
result.Result = check
If Not check Then
result.ResultMessage = "Wrong Password"
End If
Return result
End Function
End Class
Public Class ValidationManager
Private _validators As List(Of Validator)
Public Sub New()
_validators = New List(Of Validator)()
End Sub
Public Function Validate() As ValidationResult
Dim result As ValidationResult = Nothing
For Each item As var In _validators
result = item.Validate()
If Not result.Result Then
Return result
End If
Next
Return New ValidationResult() With { _
Key .Result = True, _
Key .ResultMessage = "Successfull validated" _
}
End Function
End Class
C#
public interface ILoginProvider
{
bool UserExist(int inputUserID);
bool CheckPwd(int inputUserID, string inputPwd);
}
public class LoginProvider: ILoginProvider
{
public bool UserExist(int inputUserID)
{
return true;
}
public bool CheckPwd(int inputUserID, string inputPwd)
{
return true;
}
}
public class ValidationResult
{
public bool Result { get; set; }
public string ResultMessage { get; set; }
}
public abstract class Validator
{
protected ILoginProvider _provider;
protected int _inputUserID;
protected string _inputPwd;
public Validator(ILoginProvider provider, int inputUserID, string inputPwd)
{
_provider = provider;
_inputPwd = inputPwd;
_inputUserID = inputUserID;
}
public abstract ValidationResult Validate();
}
public class UserExistenceValidator : Validator
{
public UserExistenceValidator(LoginProvider provider,int inputUserID, string inputPwd): base(provider,inputUserID, inputPwd)
{
}
public override ValidationResult Validate()
{
var result = new ValidationResult();
var check = _provider.UserExist(_inputUserID);
result.Result = check;
if(!check)
result.ResultMessage = "User Doesn't exist";
return result;
}
}
public class UserPasswordValidator : Validator
{
public UserPasswordValidator(LoginProvider provider, int inputUserID, string inputPwd)
: base(provider, inputUserID, inputPwd)
{
}
public override ValidationResult Validate()
{
var result = new ValidationResult();
var check = _provider.CheckPwd(_inputUserID, _inputPwd);
result.Result = check;
if (!check)
result.ResultMessage = "Wrong Password";
return result;
}
}
public class ValidationManager
{
List<Validator> _validators;
public ValidationManager()
{
_validators = new List<Validator>();
}
public ValidationResult Validate()
{
ValidationResult result = null;
foreach (var item in _validators)
{
result = item.Validate();
if(!result.Result)
return result;
}
return new ValidationResult(){Result = true,ResultMessage="Successfull validated" };
}
}
Use
#Function Check() As string
Dim login As New clsLogin 'assume this class handles login validation
Dim inputUserID As String 'this variable hold user id entered by user
Dim inputPwd As String 'this is password entered by user
Dim login As New LoginProvider()
Dim validators = New List(Of Validator)()
validators.Add(New UserExistenceValidator(login, 1, "test1"))
validators.Add(New UserPasswordValidator(login, 1, "test1"))
Dim manager = New ValidationManager(validators)
Dim result = manager.Validate()
return string.format("<p>{0}</p>",result.ResultMessage)
End Function
#Code
#Check()
End Code
Found it! Thx to InvernoMuto to show me how to define functions inside webpage.
First I created a class to hold login result that can provide reason if login fails.
Class LoginResult
Public Property LoginSuccess As Boolean
Public Property Reason As String
End Class
Then I created the following function for login validations
#Functions
Function CheckLogin(User As String, Pwd as String) As LoginResult
dim login As New clsLogin
Dim res as New LoginResult
res.LoginSuccess = True
if login.userExist(inputUserID) = false then
res.LoginSuccess = False
res.Reason = "User does not exist !"
return res
end if
if login.checkPwd(inputUserID, inputPwd) = false then
res.LoginSuccess = False
res.Reason = "Password mismatch !"
return res
end if
return res
End Function
End Functions
Then on the Login HTML page I just call the following code:
dim lr as LoginResult
lr = CheckLogin("someone", "password")
if lr.LoginSuccess = True then
#<p>Login Success !</p>
else
#<p>Error: #lr.Reason</p>
end if

Convert string to list of custom objects

Say I have an object Fish with properties like
Public Property ID As Integer
Public Property Name As String
Public Property Type As Integer
Public Property Age As Integer
And I have a string that looks like this:
"Fishes[0].ID=1&Fishes[0].Name=Fred&Fishes[0].Type=1&Fishes[0].Age=3&Fishes[1].ID=2&Fishes[1].Name=George&Fishes[1].Type=2&Fishes[1].Age=5&..."
Is there any way of converting/casting/whatever my string into a list of Fish objects? I can't seem to find anything to help. I do have some control over the format of the string if that would make things easier.
Many thanks
What you need to do is to parse the input string to look for Fishes[X].PROPNAME=VALUE pattern. Loop through all matches found in the string and add into or set the existing object in Dictionary. Use X as each object key in the Dictionary.
Create Fish structure:
Structure Fish
Public ID As String
Public Name As String
Public Type As Integer
Public Age As Integer
End Structure
Codes to process the input string:
Dim Fishes As New Dictionary(Of String, Fish)
Dim m As Match = Regex.Match(str, "Fishes\[(?<key>\d+)]\.(?<prop>.+?)=(?<value>[^&]+)", RegexOptions.IgnoreCase)
Do While m.Success
Dim key As String = m.Groups("key").Value.Trim.ToUpper
Dim prop As String = m.Groups("prop").Value.Trim.ToUpper
Dim value As String = m.Groups("value").Value
' if the key not yet exist in the Dictionary, create and add into it.
If Not Fishes.ContainsKey(key) Then
Fishes.Add(key, New Fish)
End If
Dim thisFish As Fish = Fishes(key) ' get the Fish object for this key
' determine the object property to set
Select Case prop
Case "ID" : thisFish.ID = value
Case "NAME" : thisFish.Name = value
Case "TYPE" : thisFish.Type = CInt(value)
Case "AGE" : thisFish.Age = CInt(value)
End Select
Fishes(key) = thisFish ' since the Fish object is declared as Structure,
' update the Dictionary item of key with the modified object.
' If Fish is declared as Class, then this line is useless
m = m.NextMatch()
Loop
Try this ..
Structure Test
Dim ID As String
Dim Name As String
Dim Type As Integer
Dim Age As Integer
End Structure
In your Button click event ..
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Fishes As New List(Of Test)
Dim Fish As New Test
Fish.ID = "GF"
Fish.Name = "Gold Fish"
Fish.Age = 1
Fish.Type = 1
Fishes.Add(Fish)
MsgBox(Fishes(0).Name)
End Sub
this is vb.net converted
Public Partial Class test
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Not IsPostBack Then
End If
End Sub
Public Sub MYtest()
Dim ls As New List(Of Fish)()
Dim f As New Fish()
f.ID = 1
f.Name = "My name"
f.Type = "My type"
f.Age = 20
ls.Add(f)
End Sub
End Class
Public Class Fish
Public Property ID() As Integer
Get
Return m_ID
End Get
Set
m_ID = Value
End Set
End Property
Private m_ID As Integer
Public Property Name() As String
Get
Return m_Name
End Get
Set
m_Name = Value
End Set
End Property
Private m_Name As String
Public Property Type() As String
Get
Return m_Type
End Get
Set
m_Type = Value
End Set
End Property
Private m_Type As String
Public Property Age() As Integer
Get
Return m_Age
End Get
Set
m_Age = Value
End Set
End Property
Private m_Age As Integer
End Class
In the comments you mentioned that this is via ASP.Net MVC. The ModelBinder will do everything for you.
public ActionResult UpdateFish(IList<Fish> listOfFish)
{
//the ModelBinder will figure out that the user has posted a list of Fish instances.
//do something with listOfFish
return View(listOfFish);
}

How can i convert the C# code listed below into VB

i am using the Json.net to serialize an object. the specific object is eventInstance.Properties which is the properties of a windows event log.
i am getting a
Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property
for C# an example is shown here
string json = JsonConvert.SerializeObject(joe, Formatting.Indented, new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
my line of code is below but i am not sure how to make it work in VB or if it is even possible
command.Parameters.AddWithValue("#f18", JsonConvert.SerializeObject(eventInstance.Properties(), New JsonSerializerSettings() {ReferenceLoopHandling = ReferenceLoopHandling.Ignore}))
i get an error that states 'ReferenceLoopHandling' is an enum type and cannot be used as an expression
thanks for the help
You can use below code:
Private Function getJSON(sJSON As String) As String
Dim objNews = New List(Of News)()
Dim news = New News()
news.id = ""
news.title = "blah"
Dim lst = New List(Of Object)()
lst.Add(New With {.video_identifier = "id1"})
lst.Add(New With {.video_identifier = "id2"})
news.video_identifier = lst.ToArray()
objNews.Add(news)
Return Newtonsoft.Json.JsonConvert.SerializeObject(New With {.data = objNews})
End Function
Class News
Public Property title As String
Get
Return _title
End Get
Set
_title = value
End Set
End Property
Private _title As String
Private _sId As String
Public Property id As String
Get
Return _sId
End Get
Set
_sId = value
End Set
End Property
Private _youtube_videos As Object() = New List(Of Object)().ToArray()
Public Property video_identifier As Object()
Get
Return _youtube_videos
End Get
Set
_youtube_videos = value
End Set
End Property
End Class
Public Class YoutubeVideos
Private _video_identifier As String
Public Property video_identifier As String
Get
Return _video_identifier
End Get
Set
_video_identifier = value
End Set
End Property
End Class

Resources