Visual Basic Language Features (VS2010 [.NET 4]) IN DEPTH

  • 0 ตอบ
  • 3469 อ่าน
*

smpksme

  • Newbie
  • *
  • 15
  • 1
    • ดูรายละเอียด
Visual Basic Language Features (VS2010 [.NET 4]) IN DEPTH
« เมื่อ: 24 มิถุนายน 2013, 07:07:56 PM »
1. Dynamic Language Runtime

โค๊ด: [Select]
Imports System.Net
Imports System.Dynamic
Imports System.Runtime.InteropServices
Imports System.Web.Script.Serialization

Public Class DynamicObject2
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim lstEpdObj As New List(Of ExpandoObject)
        Dim DynColumns As Integer = 4 'Create Dynamic 4 Columns

        For r As Integer = 0 To 10 'Create Dynamic 10 Rows
            Dim epdObj As New ExpandoObject()
            Dim p = TryCast(epdObj, IDictionary(Of String, Object))
            For c As Integer = 0 To DynColumns - 1
                p("dynColumn" & c) = "Value-" & r & c
            Next
            lstEpdObj.Add(epdObj)
        Next

        Dim p = From c In lstEpdObj.AsEnumerable()
                     Select c

        Dim dt As DataTable = ToDataTable(lstEpdObj)

        GridView1.DataSource = dt
        GridView1.DataBind()
    End Sub

    'Convert Dynamic Object To DataTable
    Public Shared Function ToDataTable(Items As List(Of ExpandoObject)) As DataTable
        Dim list = Items.Cast(Of IDictionary(Of String, Object))() '.ToList()
        If Not list.Any() Then
            Return Nothing
        End If
        Dim dt As New DataTable()
        list.First().Keys.ForEach(Function(x) dt.Columns.Add(x))
        list.ForEach(Sub(a) a.Values.ForEach(Sub(b) dt.Rows.Add(a.Values.ToArray())))
        Return dt
    End Function

    'Convert Dynamic Object To Json
    Public Shared Function ToJson(ByVal expando As ExpandoObject) As String
        Dim serializer As New JavaScriptSerializer()
        Dim json As New StringBuilder()
        Dim keyPairs As New List(Of String)()
        Dim dictionary As IDictionary(Of String, Object) = TryCast(expando, IDictionary(Of String, Object))
        json.Append("{")

        For Each pair As KeyValuePair(Of String, Object) In dictionary
            If TypeOf pair.Value Is ExpandoObject Then
                keyPairs.Add(String.Format("""{0}"": {1}", pair.Key, TryCast(pair.Value, ExpandoObject).ToList()))
            Else
                keyPairs.Add(String.Format("""{0}"": {1}", pair.Key, serializer.Serialize(pair.Value)))
            End If
        Next

        json.Append(String.Join(",", keyPairs.ToArray()))
        json.Append("}")

        Return json.ToString()
    End Function
End Class



« แก้ไขครั้งสุดท้าย: 24 มิถุนายน 2013, 07:26:56 PM โดย smpksme »