2014年4月16日水曜日

.NETでのPG間共通Configの更新方法

前回の共通ConfigでのConfig更新方法
(PGは再起動しないと取得できないので要注意)


前回は複数PGから同じConfigを参照する方法(applicationSettingだけ)を書いたけど
今回は、そのConfigの更新方法
(といってもxmlを更新する処理なだけだけどw)


いきなりサンプルソース


---------------------- コンフィグ更新用SUB[例] ----------------------------
    Public Sub WriteAppConf(ByVal sName As String, ByVal sVal As String)
        '構成ファイルのパスを取得
        Dim asm As System.Reflection.Assembly = _
            System.Reflection.Assembly.GetExecutingAssembly()
        Dim appConfigPath As String
        'ファイル指定
        appConfigPath = System.IO.Path.GetDirectoryName(asm.Location) & _
                             "TestCommon.config"
        '構成ファイルをXML DOMに読み込む
        Dim xmldoc As System.Xml.XmlDocument = New System.Xml.XmlDocument()
        xmldoc.Load(appConfigPath)
        Dim xmlnode As System.Xml.XmlNode = _
           xmldoc("TestSys.TestLibs.My.MySettings")
        'ノードを探す
        Dim n As System.Xml.XmlNode
        Dim b As Boolean = False
        For Each n In node.SelectNodes("setting")
            If n.Attributes.GetNamedItem("name").Value = sName Then
                For Each nn As System.Xml.XmlNode In n.SelectNodes("value")
                    nn.InnerText = sVal
                    b = True
                Next
                Exit For
            End If
        Next
        If Not b Then
            '新しいElementの作成
            Dim newNode As System.Xml.XmlElement = doc.CreateElement("setting")
            'Attributeを作成し、追加する
            newNode.SetAttribute("name", sName)
            newNode.SetAttribute("serializeAs", "String")
            Dim newVale As System.Xml.XmlElement = doc.CreateElement("value")
            newVale.InnerText = sVal
            newNode.AppendChild(newVale)
            node.AppendChild(newNode)
        End If
        '変更された構成ファイルを保存する
        doc.Save(appConfigPath)
    End Sub
---------------------------------------------------------------------------
   共通Configファイル名 "TestCommon.config" と
   DLL名前空間APPConfigノード名 "TestSys.TestLibs.My.MySettings" を
   環境に合わせて変更すればConfig変更用モジュールの完成


使い方は
   通常AppConfig
         my.setting.XXXX = AAAA
  共通AppConfig
         WriteAppConf("XXXX",AAAA)


ただし、文字列の情報のみ保存にしています。