Option Strict On
Imports System.xml
Imports System.Xml.Xpath
Imports System.Xml.Xsl

Imports System.IO
Imports System.Data


Public Class WebForm1
    Inherits System.Web.UI.Page

#Region " Web フォーム デザイナで生成されたコード "

    'この呼び出しは Web フォーム デザイナで必要です。
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents Button1 As System.Web.UI.WebControls.Button
    Protected WithEvents Button2 As System.Web.UI.WebControls.Button
    Protected WithEvents TextBox1 As System.Web.UI.WebControls.TextBox
    Protected WithEvents Label1 As System.Web.UI.WebControls.Label
    Protected WithEvents Label3 As System.Web.UI.WebControls.Label
    Protected WithEvents Label5 As System.Web.UI.WebControls.Label
    Protected WithEvents Label6 As System.Web.UI.WebControls.Label
    Protected WithEvents DataList1 As System.Web.UI.WebControls.DataList
    Protected WithEvents TreeView1 As Microsoft.Web.UI.WebControls.TreeView
    Protected WithEvents ListBox1 As System.Web.UI.WebControls.ListBox
    Protected WithEvents Label2 As System.Web.UI.WebControls.Label
    Protected WithEvents Button4 As System.Web.UI.WebControls.Button
    Protected WithEvents Label4 As System.Web.UI.WebControls.Label
    Protected WithEvents Button3 As System.Web.UI.WebControls.Button
   
    'メモ : 次のプレースホルダ宣言は Web フォーム デザイナで必要です。
    '削除および移動しないでください。
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        ' CODEGEN: このメソッド呼び出しは Web フォーム デザイナで必要です。
        ' コード エディタを使って変更しないでください。
        InitializeComponent()
    End Sub

#End Region
    Dim filePath As String
    Dim imageFileName As String
    Dim selectImageNo As String
    Dim categoryName As String

    Dim selectImageIndex As Integer
    Dim no As Integer

    Dim xmldoc As XPathDocument
    Dim xmldoc2 As XmlDocument
    Dim doc As XmlDocument

    Dim myImage As ImageButton

    Dim titleNode, sortNode As XmlNodeList
    Dim nameNode, imageNode As XmlNodeList
    Dim dt As DataTable

'ファイルの読み込み
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        filePath = Server.MapPath("./")

        doc = New XmlDocument
        doc.Load(filePath & "xmldata/selectCard.xml")
        nameNode = doc.SelectNodes("TREENODES/treenode/treenode/treenode/@text")
        Label4.Text = "[" & nameNode.Count & "個]の絵カードが選択されています。"
        ViewState("picNo") = nameNode.Count

        xmldoc = New XPathDocument(filePath & "cardImage/image70/categoryRainmanCard.xml")
        Dim navi As XPathNavigator = xmldoc.CreateNavigator
        Dim pattern As XPathExpression = navi.Compile("dataroot/category/@name")
        Dim categoryNode As XPathNodeIterator = navi.Select(pattern)

        While categoryNode.MoveNext
            navi = categoryNode.Current
            If Page.IsPostBack = False Then
                ListBox1.Items.Add(navi.Value)
            End If
        End While
        If Page.IsPostBack = False Then
            ListBox1.Items.Insert(0, "****//カテゴリーを選択//****")
        End If

        xmldoc = Nothing

        dt = New DataTable
        With dt.Columns
            .Add(New DataColumn("image", GetType(String)))
            .Add(New DataColumn("alt", GetType(String)))
            .Add(New DataColumn("sortNo", GetType(String)))
        End With

        TreeView1.ExpandLevel = 2
    End Sub

'カテゴリ別画像の表示
    Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
        ImageShow()
    End Sub

    Sub ImageShow()
        If ListBox1.SelectedIndex > 0 Then
            categoryName = ListBox1.SelectedItem.Text
            Label6.Text = "選択されたカテゴリーは[" & categoryName & "]です"

            xmldoc2 = New XmlDocument
            xmldoc2.Load(filePath & "cardImage/image70/categoryRainmanCard.xml")

            imageNode = xmldoc2.SelectNodes("dataroot/category[@name='" & categoryName & "']/image")
            titleNode = xmldoc2.SelectNodes("dataroot/category[@name='" & categoryName & "']/image/@alt")
            sortNode = xmldoc2.SelectNodes("dataroot/category[@name='" & categoryName & "']/image/@sortNo")

            Session("titleNode") = titleNode

            Dim dr As DataRow

            For i As Integer = 0 To imageNode.Count - 1
                dr = dt.NewRow
                dr(0) = "cardImage/image70/" & imageNode(i).InnerText
                dr(1) = titleNode(i).InnerText
                dr(2) = sortNode(i).InnerText
                dt.Rows.Add(dr)
            Next
        End If
        xmldoc2 = Nothing
        MyDataBind()
    End Sub

    Sub MyDataBind()
        DataList1.DataSource = dt
        DataList1.DataBind()
    End Sub

    Public Sub ImageNameGet(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.CommandEventArgs)
        Dim imageName As String = CType(sender, ImageButton).ImageUrl
        ViewState("imageUrl") = imageName
        'Dim titleName As String = CType(ViewState("titleName"), String)
        Dim fileLen As Integer = imageName.Length
        Dim check As Integer = InStrRev(imageName, "/")
        Dim setPos As Integer = fileLen - check
        Session("selectName") = Right(imageName, setPos)
    End Sub

'XMLツリーの生成処理
    Private Sub DataList1_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) Handles DataList1.ItemCommand
        Dim imageNo As Integer = e.Item.ItemIndex
        Dim titleName As String = CType(Session("titleNode"), XmlNodeList)(imageNo).InnerText
        Dim root As XmlNode = doc.DocumentElement.ChildNodes.Item(0).ChildNodes.Item(0)
        Dim treeNodeElement As XmlElement = doc.CreateElement("treenode")
        treeNodeElement.SetAttribute("text", titleName)
        treeNodeElement.SetAttribute("imageurl", CType(ViewState("imageUrl"), String))
        Dim treeNodeText As XmlText = doc.CreateTextNode(Nothing)
        treeNodeElement.AppendChild(treeNodeText)
        'root.AppendChild(treeNodeElement)
        root.InsertBefore(treeNodeElement, root.FirstChild)

        XmlSave()

        TreeView1.DataBind()
        ViewState("picNo") = CType(ViewState("picNo"), Integer) + 1
        Label4.Text = "[" & CType(ViewState("picNo"), String) & "個]の絵カードが登録されています。"
    End Sub

    'XMLを生成するOKボタン
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim picNo As Integer = CType(ViewState("picNo"), Integer)
        If picNo Mod 6 <> 0 Then
            With Response
                .Write("<h1>選択される画像の枚数は必ず<span style='color:red;'>6の倍数</span>にしてください！</h1>")
                .Write("画面右隅上の×マークでこのウィンドウを閉じてください！")
                .End()
            End With
        Else

            Button2.Enabled = False

            nameNode = doc.SelectNodes("TREENODES/treenode/treenode/treenode/@text")
            imageNode = doc.SelectNodes("TREENODES/treenode/treenode/treenode/@imageurl")

            Dim imageLen As Integer
            Dim lenResult As Integer
            Dim saveImage As String

            TextBox1.Text = String.Empty

            Dim strWriter As StringWriter = New StringWriter
            Dim xWriter As XmlTextWriter = New XmlTextWriter(strWriter)

            With xWriter
                .Formatting = Formatting.Indented
                .Indentation = 3
                .WriteProcessingInstruction("xml", "version='1.0' encoding='Shift_JIS'")
                .WriteStartElement("dataroot")

                Dim myData As String()
                myData = Nothing
                For i As Integer = 0 To nameNode.Count - 1
                    imageLen = InStrRev(imageNode(i).InnerText, "/")
                    lenResult = Len(imageNode(i).InnerText) - imageLen
                    saveImage = Right(imageNode(i).InnerText, lenResult)

                    .WriteStartElement("image")
                    .WriteAttributeString("alt", nameNode(i).InnerText)
                    .WriteAttributeString("sortNo", (i + 1).ToString)
                    .WriteString(saveImage)
                    .WriteEndElement()
                Next
                .WriteEndElement()
                .Flush()
                .Close()
            End With

            TextBox1.Text = strWriter.ToString
            Button2.BackColor = Color.Empty
            Button2.ForeColor = Color.Empty
            Button3.Enabled = True
            Button4.Enabled = True
            ResultXmlSave()
        End If
    End Sub

'削除処理

    Private Sub TreeView1_SelectedIndexChange(ByVal sender As Object, ByVal e As Microsoft.Web.UI.WebControls.TreeViewSelectEventArgs) Handles TreeView1.SelectedIndexChange
        Button2.Enabled = True
        Button2.BackColor = Color.Black
        Button2.ForeColor = Color.White
    End Sub

    '削除ボタン処理
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        TextBox1.Text = String.Empty

        Dim delNoLen As Integer = InStrRev(TreeView1.SelectedNodeIndex, ".")
        Dim delNoResult As Integer = Len(TreeView1.SelectedNodeIndex) - delNoLen
        Dim delNoStr As String = Right(TreeView1.SelectedNodeIndex, delNoResult)
        Dim delNo As Integer = CType(delNoStr, Integer)

        Dim root As XmlNode = doc.DocumentElement.ChildNodes.Item(0).ChildNodes.Item(0)
        root.RemoveChild(root.ChildNodes.Item(delNo))
        If File.Exists(filePath & "xmldata/selectCard.xml") = True Then File.Delete(filePath & "xmldata/selectCard.xml")
        XmlSave()
        Server.Transfer("kakunin.aspx")
    End Sub

    Sub FileDelete()
        If File.Exists(filePath & "xmldata/rainmanCard.xml") = True Then
            File.Delete(filePath & "xmldata/rainmanCard.xml")
        End If
    End Sub

'並べ替え処理
    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Dim myStrWriter As StringWriter = New StringWriter
        Dim sWriter As XmlTextWriter = New XmlTextWriter(myStrWriter)
        Dim readDoc As XPathDocument = Nothing

        readDoc = New XPathDocument(filePath & "xmldata/rainmanCard.xml")
        Dim xslt As XslTransform = New XslTransform
        xslt.Load(filePath & "xmldata/rainmanCard.xsl")

        xslt.Transform(readDoc, Nothing, myStrWriter, Nothing)
        Dim resultXml As String = myStrWriter.ToString
        Dim chikan As String = resultXml.Replace("utf-16", "Shift_JIS")
        resultXml = chikan
        TextBox1.Text = resultXml
        myStrWriter.Close()
        sWriter.Close()
    End Sub

'生成されたXMLをファイルとして保存する処理
    Sub XmlSave()
        Dim fs As FileStream = Nothing
        Dim writer As StreamWriter = Nothing
        fs = New FileStream(filePath & "xmldata/selectCard.xml", FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write)
        writer = New StreamWriter(fs, System.Text.Encoding.GetEncoding("Shift_JIS"))
        writer.Flush()
        writer.Write(doc.OuterXml)
        writer.Close()
        fs.Close()
    End Sub

    Sub ResultXmlSave()
        Dim xfs As FileStream = Nothing
        Dim myWriter As StreamWriter = Nothing

        FileDelete()

        xfs = New FileStream(filePath & "xmldata/rainmanCard.xml", FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write)
        myWriter = New StreamWriter(xfs, System.Text.Encoding.GetEncoding("Shift_JIS"))
        myWriter.Flush()
        myWriter.Write(TextBox1.Text)
        myWriter.Close()
        xfs.Close()
    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        FileDelete()
        Dim sfs As FileStream = Nothing
        Dim sWriter As StreamWriter = Nothing
        sfs = New FileStream(filePath & "xmldata/rainmanCard.xml", FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write)
        sWriter = New StreamWriter(sfs, System.Text.Encoding.GetEncoding("Shift_JIS"))
        sWriter.Flush()
        sWriter.Write(TextBox1.Text)

        sWriter.Close()
        sfs.Close()

        Dim myReadXml As XmlDocument = New XmlDocument
        myReadXml.Load(filePath & "xmldata/rainmanCard.xml")
        With Response
            .Write(myReadXml.OuterXml)
            .End()
        End With
    End Sub
End Class
