Parsing Vera User Data - Loadable as .NET Dataset

From MiOS
(Difference between revisions)
Jump to: navigation, search
 
(6 intermediate revisions by 2 users not shown)
Line 1: Line 1:
This is most likely not an elegant way to dothis, but in case someone wants something similar feel free to use this. Please suggest if there are better ways of accomplishing this and if you happen to know so, update this page :)
+
[[Category:Development]][[Category:How_To]]
  
1. This will give you a single xml file you could load in .NET through Dataset.Readxml and you will get about 14 tables.  
+
This is most likely not an elegant way to do this, but in case someone wants something similar feel free to use this. Please suggest if there are better ways of accomplishing this and if you happen to know so, update this page :)
 +
 
 +
1. This will give you a single xml file you could load in .NET through Dataset.Readxml and you will get about 48tables.  
 
<br/>
 
<br/>
 
<br/>
 
<br/>
2. Devices have states and ControlURLs , these become a separate table with a new attribute added to refer what Device ID  a row in these tables would relate to the devices table.  
+
2. Nested tables like Devices have states and ControlURLs - these become a separate table with a new attribute added to refer what Device ID  a row in these tables would relate to the devices table.  
 
<br/>
 
<br/>
 
<br/>
 
<br/>
Line 10: Line 12:
  
 
<br/>
 
<br/>
 +
Using the functions below, a small .NET web app that shows Rooms/Scenes/Devices (Code for that below)  - Also see the forum post:
  
  Sub Parse_UserData_To_DataSet(ByVal OutputFolder As String, _
+
http://forum.micasaverde.com/index.php?topic=7950.0 [http://forum.micasaverde.com/index.php?topic=7950.0]
                                          Optional ByVal veraURL As String = "http://myhome:49451")
+
  
      
+
Public Class _Default
 +
     Inherits System.Web.UI.Page
  
 +
    Dim UserDataset As DataSet
 +
    Dim ud As UserData
 +
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
 +
        If Not Page.IsPostBack Then
 +
            If Session("UserData") Is Nothing Then
 +
                ud = New UserData
 +
                Session("UserData") = ud.Parse_UserData_To_DataSet("d:\test")
 +
            End If
 +
        End If
 +
        UserDataset = Session("UserData")
 +
        GetData()
 +
    End Sub
  
         'Parse XML and create XML files to load in to dataset directly
+
    Sub GetData()
         Dim ControlURL As New StringBuilder("<ControlURLs>" & vbCrLf)
+
         Dim RoomsTable As DataTable = UserDataset.Tables("rooms")
         Dim States As New StringBuilder("<states>" & vbCrLf)
+
        Me.RoomsGrid.DataSource = RoomsTable
         Dim Entries As New ArrayList
+
        Me.RoomsGrid.DataBind()
 +
        RoomsGrid.ShowHeader = False
 +
         Dim ScenesTable As DataTable = UserDataset.Tables("scenes")
 +
        Me.ScenesGrid.DataSource = ScenesTable
 +
        Me.ScenesGrid.DataBind()
 +
        ScenesGrid.ShowHeader = False
 +
         Dim DevicesTable As DataTable = UserDataset.Tables("devices")
 +
         Dim drRemove As DataRow() = DevicesTable.Select("invisible=1")
 +
        For Each dr As DataRow In drRemove
 +
            DevicesTable.Rows.Remove(dr)
 +
        Next
 +
        Me.DevicesGrid.DataSource = DevicesTable
 +
        Me.DevicesGrid.DataBind()
 +
        DevicesGrid.ShowHeader = False
 +
    End Sub
  
 +
End Class
 +
 +
<br/>
 +
So, This is more like it!!!
 +
<br/>
 +
 +
Dim masterDs As New DataSet
 +
 +
    Sub Parse_UserData_To_DataSet(ByVal OutputFolder As String, _
 +
                                          Optional ByVal veraURL As String = "http://myhome:49451")
 +
        'Parse XML and create XML files to load in to dataset directly
 
         Dim settings As New XmlReaderSettings()
 
         Dim settings As New XmlReaderSettings()
 
         settings.DtdProcessing = DtdProcessing.Parse
 
         settings.DtdProcessing = DtdProcessing.Parse
Line 28: Line 68:
 
         doc.Load(reader)
 
         doc.Load(reader)
 
         Dim root As XmlNode = doc.DocumentElement
 
         Dim root As XmlNode = doc.DocumentElement
         Dim fout As New StreamWriter(Path.Combine(OutputFolder, root.Name & ".xml"))
+
         Dim ParseNodeEnum As IEnumerator = root.GetEnumerator
        Dim ienumroot As IEnumerator = root.Attributes.GetEnumerator()
+
         While (ParseNodeEnum.MoveNext)
         fout.Write("<root ")
+
             Dim NodeRow As XmlNode = ParseNodeEnum.Current
        While ienumroot.MoveNext
+
             ParseElements(NodeRow, Nothing)
             Dim atr As XmlAttribute = ienumroot.Current
+
             fout.Write(atr.Name & "=" & """" & atr.Value & """ ")
+
 
         End While
 
         End While
        fout.Write("></root>" & vbCrLf)
+
    End Sub
        fout.Close()
+
        Entries.Add(Path.Combine(OutputFolder, root.Name & ".xml"))
+
 
+
        Dim ienum As IEnumerator = root.GetEnumerator()
+
        Dim ParseNode As XmlNode
+
        While (ienum.MoveNext())
+
            ParseNode = CType(ienum.Current, XmlNode)
+
            fout = New StreamWriter(Path.Combine(OutputFolder, ParseNode.Name & ".xml"))
+
            fout.Write(ParseNode.OuterXml)
+
            fout.Close()
+
            Entries.Add(Path.Combine(OutputFolder, ParseNode.Name & ".xml"))
+
            If ParseNode.Name <> "devices" Then Continue While
+
  
            'Get States / ControlURLS also as seperate table
+
    Sub ParseElements(ByVal ParseNode As XmlNode, ByVal ParentRow As DataRow)
            Dim ServiceID As Integer = 1
+
        Dim dt As DataTable = CreateTable(ParseNode, ParentRow)
            Dim DeviceDetails As XmlNode
+
        Dim ParseNodeEnum As IEnumerator = ParseNode.GetEnumerator
            Dim devenum As IEnumerator = ParseNode.GetEnumerator
+
        While (ParseNodeEnum.MoveNext)
            '-------Devices Loop
+
            Dim NodeRow As XmlNode = ParseNodeEnum.Current
            While (devenum.MoveNext)
+
            Dim dr As DataRow = dt.NewRow
                DeviceDetails = CType(devenum.Current, XmlNode)
+
            'Add Attributes as columns to Datatable
                Dim DeviceID As String = DeviceDetails.Attributes.GetNamedItem("id").InnerText
+
            Dim ienum As IEnumerator = NodeRow.Attributes.GetEnumerator()
 
+
            While ienum.MoveNext
                Dim devChildNode As XmlNode
+
                Dim atr As XmlAttribute = ienum.Current
                Dim devChildNodeInner As XmlNode
+
                If dt.Columns.Contains(atr.Name) = False Then dt.Columns.Add(atr.Name)
                Dim childEnum As IEnumerator = DeviceDetails.GetEnumerator
+
                dr(atr.Name) = atr.Value
                While childEnum.MoveNext
+
                    devChildNode = CType(childEnum.Current, XmlNode)
+
                    Dim childEnumInner As IEnumerator = devChildNode.GetEnumerator
+
                    While childEnumInner.MoveNext
+
                        devChildNodeInner = childEnumInner.Current
+
 
+
                        Dim DeviceIDAttr As XmlAttribute = doc.CreateAttribute("DeviceID")
+
                        DeviceIDAttr.InnerText = DeviceID
+
                        devChildNodeInner.Attributes.Append(DeviceIDAttr)
+
 
+
                        If devChildNode.OuterXml.StartsWith("<state") Then
+
                            States.Append(devChildNodeInner.OuterXml & vbCrLf)
+
                        Else
+
                            Dim serviceIDstr As String = "<service_" & ServiceID
+
                            Dim strtoWrite As String = devChildNodeInner.OuterXml.Replace(serviceIDstr, "<service ID=""" & ServiceID & """ ")
+
                            strtoWrite = strtoWrite.Replace("</service_" & ServiceID & ">", "</service>")
+
                            ControlURL.Append(strtoWrite & vbCrLf)
+
                            ServiceID += 1
+
                        End If
+
                    End While
+
                End While
+
 
             End While
 
             End While
             '------Devices Loop
+
             If Not IsNothing(ParentRow) Then
 
+
                Dim ParentColumn As String = ParentRow.Table.TableName & "_OurID"
 +
                If dt.Columns.Contains(ParentColumn) Then dr(ParentColumn) = ParentRow(ParentColumn)
 +
            End If
 +
            dt.Rows.Add(dr)
 +
            For Each x As XmlNode In NodeRow.ChildNodes
 +
                ParseElements(x, dr)
 +
            Next
 
         End While
 
         End While
 +
        If Not masterDs.Tables.Contains(ParseNode.Name) Then masterDs.Tables.Add(dt)
 +
    End Sub
  
        States.Append("</states>" & vbCrLf)
+
    Function CreateTable(ByVal Node As XmlNode, ByVal ParentRow As DataRow) As DataTable
         fout = New StreamWriter(Path.Combine(OutputFolder, "states.xml"))
+
         Dim dt As DataTable
        fout.Write(States.ToString)
+
        If masterDs.Tables.Contains(Node.Name) Then
         fout.Close()
+
            dt = masterDs.Tables(Node.Name)
 
+
            Return dt
         ControlURL.Append("</ControlURLs>" & vbCrLf)
+
         End If
         fout = New StreamWriter(Path.Combine(OutputFolder, "ControlURL.xml"))
+
        dt = New DataTable(Node.Name)
        fout.Write(ControlURL.ToString)
+
        'Add primary key col
         fout.Close()
+
         Dim KeyColumn As String = Node.Name & "_OurID"
         Entries.Add(Path.Combine(OutputFolder, "states.xml"))
+
         dt.Columns.Add(New DataColumn(KeyColumn, GetType(System.Int32)))
        Entries.Add(Path.Combine(OutputFolder, "ControlURL.xml"))
+
         dt.Columns(0).AutoIncrement = True
         'Parsing Done
+
         dt.Constraints.Add(dt.TableName & "PrimaryID", dt.Columns(0), True)
 
+
         'Add parent ref column
         'Create a Single XML file so it can be loaded in to dataset with Dataset.ReadXML
+
         If Not IsNothing(ParentRow) Then
        Dim finalDS As New DataSet
+
            Dim ParentColumn As String = ParentRow.Table.TableName & "_OurID"
        For Each fname As String In Entries
+
             dt.Columns.Add(New DataColumn(ParentColumn, GetType(System.Int32)))
 
+
        End If
            Dim ds As New DataSet
+
         Return dt
            ds.ReadXml(fname)
+
     End Function
             Try
+
                finalDS.Tables.Add(ds.Tables(0).Copy)
+
                finalDS.Tables(finalDS.Tables.Count - 1).TableName = ds.Tables(0).TableName
+
            Catch ex As Exception
+
            End Try
+
         Next
+
        finalDS.WriteXml(Path.Combine(OutputFolder, "UserData.xml"))
+
 
+
     End Sub
+

Latest revision as of 03:17, 15 June 2013


This is most likely not an elegant way to do this, but in case someone wants something similar feel free to use this. Please suggest if there are better ways of accomplishing this and if you happen to know so, update this page :)

1. This will give you a single xml file you could load in .NET through Dataset.Readxml and you will get about 48tables.

2. Nested tables like Devices have states and ControlURLs - these become a separate table with a new attribute added to refer what Device ID a row in these tables would relate to the devices table.

Parse.jpg


Using the functions below, a small .NET web app that shows Rooms/Scenes/Devices (Code for that below) - Also see the forum post:

http://forum.micasaverde.com/index.php?topic=7950.0 [1]

Public Class _Default

   Inherits System.Web.UI.Page
   Dim UserDataset As DataSet
   Dim ud As UserData
   Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
       If Not Page.IsPostBack Then
           If Session("UserData") Is Nothing Then
               ud = New UserData
               Session("UserData") = ud.Parse_UserData_To_DataSet("d:\test")
           End If
       End If
       UserDataset = Session("UserData")
       GetData()
   End Sub
   Sub GetData()
       Dim RoomsTable As DataTable = UserDataset.Tables("rooms")
       Me.RoomsGrid.DataSource = RoomsTable
       Me.RoomsGrid.DataBind()
       RoomsGrid.ShowHeader = False
       Dim ScenesTable As DataTable = UserDataset.Tables("scenes")
       Me.ScenesGrid.DataSource = ScenesTable
       Me.ScenesGrid.DataBind()
       ScenesGrid.ShowHeader = False
       Dim DevicesTable As DataTable = UserDataset.Tables("devices")
       Dim drRemove As DataRow() = DevicesTable.Select("invisible=1")
       For Each dr As DataRow In drRemove
           DevicesTable.Rows.Remove(dr)
       Next
       Me.DevicesGrid.DataSource = DevicesTable
       Me.DevicesGrid.DataBind()
       DevicesGrid.ShowHeader = False
   End Sub

End Class


So, This is more like it!!!

Dim masterDs As New DataSet
   Sub Parse_UserData_To_DataSet(ByVal OutputFolder As String, _
                                         Optional ByVal veraURL As String = "http://myhome:49451")
       'Parse XML and create XML files to load in to dataset directly
       Dim settings As New XmlReaderSettings()
       settings.DtdProcessing = DtdProcessing.Parse
       Dim reader As XmlReader = XmlReader.Create(veraURL & "/data_request?output_format=xml&id=user_data", settings)
       Dim doc As New XmlDocument()
       doc.Load(reader)
       Dim root As XmlNode = doc.DocumentElement
       Dim ParseNodeEnum As IEnumerator = root.GetEnumerator
       While (ParseNodeEnum.MoveNext)
           Dim NodeRow As XmlNode = ParseNodeEnum.Current
           ParseElements(NodeRow, Nothing)
       End While
   End Sub
   Sub ParseElements(ByVal ParseNode As XmlNode, ByVal ParentRow As DataRow)
       Dim dt As DataTable = CreateTable(ParseNode, ParentRow)
       Dim ParseNodeEnum As IEnumerator = ParseNode.GetEnumerator
       While (ParseNodeEnum.MoveNext)
           Dim NodeRow As XmlNode = ParseNodeEnum.Current
           Dim dr As DataRow = dt.NewRow
           'Add Attributes as columns to Datatable
           Dim ienum As IEnumerator = NodeRow.Attributes.GetEnumerator()
           While ienum.MoveNext
               Dim atr As XmlAttribute = ienum.Current
               If dt.Columns.Contains(atr.Name) = False Then dt.Columns.Add(atr.Name)
               dr(atr.Name) = atr.Value
           End While
           If Not IsNothing(ParentRow) Then
               Dim ParentColumn As String = ParentRow.Table.TableName & "_OurID"
               If dt.Columns.Contains(ParentColumn) Then dr(ParentColumn) = ParentRow(ParentColumn)
           End If
           dt.Rows.Add(dr)
           For Each x As XmlNode In NodeRow.ChildNodes
               ParseElements(x, dr)
           Next
       End While
       If Not masterDs.Tables.Contains(ParseNode.Name) Then masterDs.Tables.Add(dt)
   End Sub
   Function CreateTable(ByVal Node As XmlNode, ByVal ParentRow As DataRow) As DataTable
       Dim dt As DataTable
       If masterDs.Tables.Contains(Node.Name) Then
           dt = masterDs.Tables(Node.Name)
           Return dt
       End If
       dt = New DataTable(Node.Name)
       'Add primary key col
       Dim KeyColumn As String = Node.Name & "_OurID"
       dt.Columns.Add(New DataColumn(KeyColumn, GetType(System.Int32)))
       dt.Columns(0).AutoIncrement = True
       dt.Constraints.Add(dt.TableName & "PrimaryID", dt.Columns(0), True)
       'Add parent ref column
       If Not IsNothing(ParentRow) Then
           Dim ParentColumn As String = ParentRow.Table.TableName & "_OurID"
           dt.Columns.Add(New DataColumn(ParentColumn, GetType(System.Int32)))
       End If
       Return dt
   End Function
Personal tools