posted by 방랑군 2009. 9. 24. 13:47


App.config

<?xml version="1.0" encoding="utf-8" ?>

<configuration>


  <configSections>

    <section name="unity" type="Console_Config_User.UserInfo,Console_Config_User" />

  </configSections>


  <unity>

    <NAME>황승재</NAME>

    <ADDRESS>염창동</ADDRESS>

    <HP>016-647-0678</HP>

  </unity>

</configuration>


unity.xml - 객체만들 부분만 뽑아서 XML 만든다.

<?xml version="1.0" encoding="utf-8" ?>

<unity>

  <NAME>황승재</NAME>

  <ADDRESS AD1="서울시" AD2="염창동" AD3="동아3차아파트" AD4="307동 1101호" />

  <HP>016-647-0678</HP>

</unity> 



XSD.EXE 로 XSD 파일 만들고 CLASS 객체 파일 만든다.

>xsd.exe unity.xml


>xsd.exe unity.xsd /c


unity.cs

//------------------------------------------------------------------------------

// <auto-generated>

//     This code was generated by a tool.

//     Runtime Version:2.0.50727.3082

//

//     Changes to this file may cause incorrect behavior and will be lost if

//     the code is regenerated.

// </auto-generated>

//------------------------------------------------------------------------------


using System.Xml.Serialization;


// 

// This source code was auto-generated by xsd, Version=2.0.50727.1432.

// 

namespace Console_Config_User

{


    /// <remarks/>

    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")]

    [System.SerializableAttribute()]

    [System.Diagnostics.DebuggerStepThroughAttribute()]

    [System.ComponentModel.DesignerCategoryAttribute("code")]

    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]

    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]

    public partial class unity

    {


        private string nAMEField;


        private string hpField;


        private unityADDRESS[] aDDRESSField;


        /// <remarks/>

        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]

        public string NAME

        {

            get

            {

                return this.nAMEField;

            }

            set

            {

                this.nAMEField = value;

            }

        }


        /// <remarks/>

        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]

        public string HP

        {

            get

            {

                return this.hpField;

            }

            set

            {

                this.hpField = value;

            }

        }


        /// <remarks/>

        [System.Xml.Serialization.XmlElementAttribute("ADDRESS", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]

        public unityADDRESS[] ADDRESS

        {

            get

            {

                return this.aDDRESSField;

            }

            set

            {

                this.aDDRESSField = value;

            }

        }

    }


    /// <remarks/>

    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")]

    [System.SerializableAttribute()]

    [System.Diagnostics.DebuggerStepThroughAttribute()]

    [System.ComponentModel.DesignerCategoryAttribute("code")]

    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]

    public partial class unityADDRESS

    {


        private string aD1Field;


        private string aD2Field;


        private string aD3Field;


        private string aD4Field;


        /// <remarks/>

        [System.Xml.Serialization.XmlAttributeAttribute()]

        public string AD1

        {

            get

            {

                return this.aD1Field;

            }

            set

            {

                this.aD1Field = value;

            }

        }


        /// <remarks/>

        [System.Xml.Serialization.XmlAttributeAttribute()]

        public string AD2

        {

            get

            {

                return this.aD2Field;

            }

            set

            {

                this.aD2Field = value;

            }

        }


        /// <remarks/>

        [System.Xml.Serialization.XmlAttributeAttribute()]

        public string AD3

        {

            get

            {

                return this.aD3Field;

            }

            set

            {

                this.aD3Field = value;

            }

        }


        /// <remarks/>

        [System.Xml.Serialization.XmlAttributeAttribute()]

        public string AD4

        {

            get

            {

                return this.aD4Field;

            }

            set

            {

                this.aD4Field = value;

            }

        }

    }


    /// <remarks/>

    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")]

    [System.SerializableAttribute()]

    [System.Diagnostics.DebuggerStepThroughAttribute()]

    [System.ComponentModel.DesignerCategoryAttribute("code")]

    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]

    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]

    public partial class NewDataSet

    {


        private unity[] itemsField;


        /// <remarks/>

        [System.Xml.Serialization.XmlElementAttribute("unity")]

        public unity[] Items

        {

            get

            {

                return this.itemsField;

            }

            set

            {

                this.itemsField = value;

            }

        }

    }

}



UserInfo.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;


using System.Configuration;

using System.Xml;


namespace Console_Config_User

{

    class UserInfo : System.Configuration.IConfigurationSectionHandler

    {


#region IConfigurationSectionHandler 멤버


public object Create(object parent, object configContext, System.Xml.XmlNode section)

{

    //throw new NotImplementedException();

    XmlDocument doc = new XmlDocument();

    doc.LoadXml(section.OuterXml);

    Console_Config_User.unity objClass = new unity();

    objClass = (unity)xxml.ToInstance(doc, typeof(unity));


    return objClass;

}


#endregion

    }

}



Program.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;


using System.Configuration;


namespace Console_Config_User

{

    class Program

    {

        static void Main(string[] args)

        {


            //object config = ConfigurationManager.GetSection("unity");


            unity container = new unity();

            container = (unity)ConfigurationManager.GetSection("unity");

            

        }

    }

}




결과.





posted by 방랑군 2009. 9. 24. 11:27

첨부파일 :

XMLFile2.xml

<?xml version="1.0" encoding="UTF-8" ?>

<Root>

  <Record>

    <Field1>Field1_0</Field1>

    <Field2>Field2_0</Field2>

  </Record>

  <Record2 Field2="Field2_0" Field3="Field3_1" />

  <Field1>Field1_0</Field1>

  <Field2>Field2_0</Field2>

</Root>




>xsd.exe XMLFile2.xml
XMLFile2.xml

<?xml version="1.0" encoding="utf-8"?>

<xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">

  <xs:element name="Root">

    <xs:complexType>

      <xs:sequence>

        <xs:element name="Field1" type="xs:string" minOccurs="0" />

        <xs:element name="Field2" type="xs:string" minOccurs="0" />

        <xs:element name="Record" minOccurs="0" maxOccurs="unbounded">

          <xs:complexType>

            <xs:sequence>

              <xs:element name="Field1" type="xs:string" minOccurs="0" />

              <xs:element name="Field2" type="xs:string" minOccurs="0" />

            </xs:sequence>

          </xs:complexType>

        </xs:element>

        <xs:element name="Record2" minOccurs="0" maxOccurs="unbounded">

          <xs:complexType>

            <xs:attribute name="Field2" type="xs:string" />

            <xs:attribute name="Field3" type="xs:string" />

          </xs:complexType>

        </xs:element>

      </xs:sequence>

    </xs:complexType>

  </xs:element>

  <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">

    <xs:complexType>

      <xs:choice minOccurs="0" maxOccurs="unbounded">

        <xs:element ref="Root" />

      </xs:choice>

    </xs:complexType>

  </xs:element>

</xs:schema>


>xsd.exe XMLFile2.xsd /c
XMLFile2.cs

//------------------------------------------------------------------------------

// <auto-generated>

//     This code was generated by a tool.

//     Runtime Version:2.0.50727.3082

//

//     Changes to this file may cause incorrect behavior and will be lost if

//     the code is regenerated.

// </auto-generated>

//------------------------------------------------------------------------------


using System.Xml.Serialization;


// 

// This source code was auto-generated by xsd, Version=2.0.50727.1432.

// 



/// <remarks/>

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")]

[System.SerializableAttribute()]

[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.ComponentModel.DesignerCategoryAttribute("code")]

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]

[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]

public partial class Root {

    

    private string field1Field;

    

    private string field2Field;

    

    private RootRecord[] recordField;

    

    private RootRecord2[] record2Field;

    

    /// <remarks/>

    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]

    public string Field1 {

        get {

            return this.field1Field;

        }

        set {

            this.field1Field = value;

        }

    }

    

    /// <remarks/>

    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]

    public string Field2 {

        get {

            return this.field2Field;

        }

        set {

            this.field2Field = value;

        }

    }

    

    /// <remarks/>

    [System.Xml.Serialization.XmlElementAttribute("Record", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]

    public RootRecord[] Record {

        get {

            return this.recordField;

        }

        set {

            this.recordField = value;

        }

    }

    

    /// <remarks/>

    [System.Xml.Serialization.XmlElementAttribute("Record2", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]

    public RootRecord2[] Record2 {

        get {

            return this.record2Field;

        }

        set {

            this.record2Field = value;

        }

    }

}


/// <remarks/>

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")]

[System.SerializableAttribute()]

[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.ComponentModel.DesignerCategoryAttribute("code")]

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]

public partial class RootRecord {

    

    private string field1Field;

    

    private string field2Field;

    

    /// <remarks/>

    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]

    public string Field1 {

        get {

            return this.field1Field;

        }

        set {

            this.field1Field = value;

        }

    }

    

    /// <remarks/>

    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]

    public string Field2 {

        get {

            return this.field2Field;

        }

        set {

            this.field2Field = value;

        }

    }

}


/// <remarks/>

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")]

[System.SerializableAttribute()]

[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.ComponentModel.DesignerCategoryAttribute("code")]

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]

public partial class RootRecord2 {

    

    private string field2Field;

    

    private string field3Field;

    

    /// <remarks/>

    [System.Xml.Serialization.XmlAttributeAttribute()]

    public string Field2 {

        get {

            return this.field2Field;

        }

        set {

            this.field2Field = value;

        }

    }

    

    /// <remarks/>

    [System.Xml.Serialization.XmlAttributeAttribute()]

    public string Field3 {

        get {

            return this.field3Field;

        }

        set {

            this.field3Field = value;

        }

    }

}


/// <remarks/>

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")]

[System.SerializableAttribute()]

[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.ComponentModel.DesignerCategoryAttribute("code")]

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]

[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]

public partial class NewDataSet {

    

    private Root[] itemsField;

    

    /// <remarks/>

    [System.Xml.Serialization.XmlElementAttribute("Root")]

    public Root[] Items {

        get {

            return this.itemsField;

        }

        set {

            this.itemsField = value;

        }

    }

}




쓸데없는 Attribute 제거 후 객체 모양

using System.IO;

using System.Xml;

using System.Xml.Serialization;


using System.Collections.Generic;

using System.Linq;

using System.Text;



namespace Console_XML.In4

{


    /// <remarks/>

    [System.Serializable]

    //[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]

    public class Root

    { 


        /// <remarks/>

        

        public RootRecord Record

        {

            get { return _Record; }

            set { _Record = value; }

        }

        private RootRecord _Record = new RootRecord();



        /// <remarks/>

        

        public RootRecord2 Record2

        {

            get { return _Record2; }

            set { _Record2 = value; }

        }

        private RootRecord2 _Record2 = new RootRecord2();



        /// <remarks/>

        

        public string Field1

        {

            get { return _Field1; }

            set { _Field1 = value; }

        }

        private string _Field1 = "";



        /// <remarks/>

        

        public string Field2

        {

            get { return _Field2; }

            set { _Field2 = value; }

        }

        private string _Field2 = "";


    }


    /// <remarks/>

    [System.Serializable]    

    public class RootRecord

    {


        /// <remarks/>

        

        public string Field1

        {

            get { return _Field1; }

            set { _Field1 = value; }

        }

        private string _Field1 = "";



        /// <remarks/>

        

        public string Field2

        {

            get { return _Field2; }

            set { _Field2 = value; }

        }

        private string _Field2 = "";


    }


    /// <remarks/>

    [System.Serializable]    

    public class RootRecord2

    {


        /// <remarks/>

        [System.Xml.Serialization.XmlAttributeAttribute()]

        public string Field2

        {

            get { return _Field2; }

            set { _Field2 = value; }

        }

        private string _Field2 = "";



        /// <remarks/>

        [System.Xml.Serialization.XmlAttributeAttribute()]

        public string Field3

        {

            get { return _Field3; }

            set { _Field3 = value; }

        }

        private string _Field3 = "";


    }


}



XML <-> CLASS 할 함수

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



using System.Xml;

using System.IO;

using System.Xml.Serialization;



namespace Console_XML

{

    class xxml

    {


        /// <summary>

        /// XML -> yyyyMMdd\FILE

        /// </summary>

        /// <param name="doc"></param>

        /// <param name="path"></param>

        public static void XMLDoctoFile(XmlDocument doc, string path)

        {

            string _Date = DateTime.Now.ToString("yyyyMMdd", System.Globalization.DateTimeFormatInfo.InvariantInfo);

            string[] _path = path.Split(new char[] { '\\' });

            string _fullpath = "";

            for (int i = 0; i < _path.Length - 1; i++)

            {

                _fullpath += _path[i] + "\\";


            }

            // 디렉토리 검색

            if (!System.IO.Directory.Exists(_fullpath + "\\" + _Date))

            {

                Directory.CreateDirectory(_fullpath + "\\" + _Date);

            }


            path = _fullpath + "\\" + _Date + "\\" + _path[_path.Length - 1];


            XmlTextWriter writer = new XmlTextWriter(path, new UTF8Encoding());

            try

            {

                writer.Formatting = Formatting.Indented;

                writer.Indentation = 4;

                doc.WriteContentTo(writer);

            }

            finally

            {

                writer.Close();

            }

        }



        /// <summary>

        /// XML -> yyyyMMdd\FILE

        /// </summary>

        /// <param name="doc"></param>

        /// <param name="path"></param>

        public static void XMLDoctoFileEx(XmlDocument doc, string path)

        {

            string _Date = DateTime.Now.ToString("yyyyMMdd", System.Globalization.DateTimeFormatInfo.InvariantInfo);

            string _Hour = DateTime.Now.ToString("HH", System.Globalization.DateTimeFormatInfo.InvariantInfo);

            string[] _path = path.Split(new char[] { '\\' });

            string _dirPath = "";

            string _fullpath = "";

            for (int i = 0; i < _path.Length - 1; i++)

            {

                _fullpath += _path[i] + "\\";


            }


            _dirPath = _fullpath + "\\" + _Date + "\\" + _Hour;

            // 디렉토리 검색

            if (!System.IO.Directory.Exists(_dirPath))

            {

                Directory.CreateDirectory(_dirPath);

            }


            path = _dirPath + "\\" + _path[_path.Length - 1];


            XmlTextWriter writer = new XmlTextWriter(path, new UTF8Encoding());

            try

            {

                writer.Formatting = Formatting.Indented;

                writer.Indentation = 4;

                doc.WriteContentTo(writer);

            }

            catch (Exception err)

            {

                System.Diagnostics.EventLog.WriteEntry("VTFramework", "[vS_XML:XMLDoctoFileEx]:" + err.Message, System.Diagnostics.EventLogEntryType.Error);

            }

            finally

            {

                writer.Close();

            }

        }


        /// <summary>

        /// 객체를 xmlDocument로 전환 하는 함수.

        /// </summary>

        /// <param name="obj"></param>

        /// <returns></returns>

        public static XmlDocument ToMessage(object obj)

        {

            try

            {

                XmlSerializer serializer = new XmlSerializer(obj.GetType());

                MemoryStream stream = new MemoryStream();

                StreamReader reader = new StreamReader(stream);

                serializer.Serialize(stream, obj);

                stream.Position = 0;

                XmlDocument doc = new XmlDocument();

                doc.LoadXml(reader.ReadToEnd());

                try

                {

                    return doc;

                }

                finally

                {

                    reader.Close();

                    stream.Close();

                }

            }

            catch (Exception exc)

            {

                System.Diagnostics.EventLog.WriteEntry("VTFramework", "[vS_XML:ToMessage]:" + exc.Message, System.Diagnostics.EventLogEntryType.Error);

                throw new Exception("객체 생성중 오류가 발생했읍니다![ToInstance", exc);

            }

        }


        /// <summary>

        /// xmlDocument를 객체로 변환하는 함수

        ///  XML -> CLASS

        /// ex)

        ///   1. 변환할 클래스의 필드가 적어도 많아도 적용이 됨

        ///   2. 다른 필드가 존재해도 적용이 됨

        /// </summary>

        /// <param name="doc"></param>

        /// <param name="type"></param>

        /// <returns></returns>

        public static object ToInstance(XmlDocument doc, System.Type type)

        {

            try

            {

                XmlSerializer serializer = new XmlSerializer(type);

                MemoryStream writeStream = new MemoryStream();

                MemoryStream readStream = new MemoryStream();


                XmlTextWriter writer = new XmlTextWriter(writeStream, null);

                doc.WriteContentTo(writer);

                writer.Flush();


                writeStream.Position = 0;


                writeStream.WriteTo(readStream);

                writer.Close();

                writeStream.Close();


                readStream.Position = 0;

                XmlTextReader reader = new XmlTextReader(readStream);

                try

                {

                    return serializer.Deserialize(reader);

                }

                finally

                {

                    reader.Close();

                    readStream.Close();

                }

            }

            catch (Exception exc)

            {

                throw new Exception("객체 생성중 오류가 발생했읍니다![ToInstance", exc);

            }

        }

    }

}




XML -> CLASS 객체로 변환 소스

doc.Load(@"XMLFile2.xml");


Console_XML.In4.Root objInstance3 = (Console_XML.In4.Root)xxml.ToInstance(doc, typeof(Console_XML.In4.Root));


posted by 방랑군 2009. 9. 23. 15:23

        static void Main(string[] args)

        {



            StringBuilder strXML = new StringBuilder(); 

            strXML.AppendLine(@"<?xml version=""1.0"" encoding=""utf-8"" ?>");

            strXML.AppendLine(@"<unity>");

            strXML.AppendLine(@"<NAME>황승재</NAME>");

            strXML.AppendLine(@"<ADDRESS AD1=""서울시"" AD2=""염창동"" AD3=""동아3차아파트"" AD4=""307동 1101호"" />");

            strXML.AppendLine(@"<HP>016-647-0678</HP>");

            strXML.AppendLine(@"</unity>");

            strXML.AppendLine("");



            XmlDocument doc = new XmlDocument();

            doc.LoadXml(strXML.ToString());


            ///

            ///

            string strNode1 = doc.SelectSingleNode("unity/NAME").InnerText;

            string strNode2 = doc.SelectSingleNode("unity/ADDRESS").Attributes["AD1"].Value;



            doc = null;

        }




posted by 방랑군 2009. 9. 23. 14:48


  <unity>

    <NAME>황승재</NAME>

    <ADDRESS AD1="서울시" AD2="염창동" AD3="동아3차아파트" AD4="307동 1101호" />

    <HP>016-647-0678</HP>

  </unity>


ADDRESS 의 Attribute 값 가져오는 법


section.SelectSingleNode("ADDRESS").Attributes["AD1"].Value

"서울시"


/// 더미..

section.SelectSingleNode("ADDRESS").OuterXml

"<ADDRESS AD1=\"서울시\" AD2=\"염창동\" AD3=\"동아3차아파트\" AD4=\"307동 1101호\" />"

section.SelectSingleNode("ADDRESS").Attributes["AD1"].OuterXml

"AD1=\"서울시\""




ADDRESS 의 Element 값 가져오는 법

section.SelectSingleNode("NAME").InnerText; 

"황승재"



IConfigurationSectionHandler  에서 값 할당

#region IConfigurationSectionHandler 멤버


public object Create(object parent, object configContext, System.Xml.XmlNode section)

{

    //throw new NotImplementedException();


    UserInfo obj = new UserInfo();


    

    obj._NAME    = section.SelectSingleNode("NAME").InnerText; // section 이용하여 config 값 넣는다.  

    obj._ADDRESS = doc.SelectSingleNode("unity/ADDRESS").Attributes["AD1"].Value;

    obj._HP      = section.SelectSingleNode("HP").InnerText; // section 이용하여 config 값 넣는다.

    return obj;

}


#endregion


posted by 방랑군 2009. 9. 23. 14:24



Understanding Section Handlers - App.config File

참조 : http://www.codeproject.com/KB/aspnet/ConfigSections.aspx


예제 Config

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

//1 SECTIOIN 구성등

<configSections>

<sectionGroup name="settings">

<section name="dbSettings" type="System.Configuration.NameValueSectionHandler"/>

</sectionGroup>

<sectionGroup name="inputScreen">

<section name="education" type="System.Configuration.DictionarySectionHandler"/>

<section name="sex" type="System.Configuration.SingleTagSectionHandler"/>

</sectionGroup>

<sectionGroup name="companyInfo">

<section name="companyAddress" type="ConfigSections.MyConfigHandler,ConfigSections"/>

</sectionGroup>

</configSections>


<settings>

<dbSettings>

<add key="connectionString" value="Data Source=localhost;Initial Catalog=Northwind;"/>

<add key="imagesPath" value="c:\MyApp\Resources\Images\"/>

</dbSettings>

</settings>


<inputScreen>

<education>

<add key="1" value="High School"/>

<add key="2" value="Bachelors"/>

<add key="3" value="Masters"/>

<add key="4" value="Doctorate"/>

</education>

<sex Male="1" Female="2"/>

</inputScreen>


<companyInfo> 

<companyAddress> 

<companyName>Axxonet Solutions India Pvt Ltd</companyName>

<doorNo>1301</doorNo>

<street>13th Cross, Indira Nagar, 2nd Stage</street>

<city>Bangalore</city>

<postalCode>560038</postalCode>

<country>India</country>

</companyAddress>

</companyInfo>


<!--

Read appsettings from an external file.

-->

<appSettings file="appSettings.xml"/>

<appSettings>

<add key="author" value="Palanisamy Veerasingam"/>

<add key="article" value="Configuration Sections"/>

</appSettings>

</configuration>


.NET 1.1 호출 밥법

NameValueCollection nvc=(NameValueCollection)ConfigurationSettings.GetConfig("settings/dbSettings");

            MessageBox.Show("Connection String is " + nvc[0].ToString() );



Hashtable objHash=(Hashtable) ConfigurationSettings.GetConfig("inputScreen/education");

MessageBox.Show("Education list count is " + objHash.Count);


Hashtable objHash=(Hashtable) ConfigurationSettings.GetConfig("inputScreen/sex");

MessageBox.Show("Value of male is " + objHash["Male"].ToString() );

CCompanyAddr obj=(CCompanyAddr)ConfigurationSettings.GetConfig("companyInfo/companyAddress"); 

string strMsg;

strMsg = "Company Address is:\n" +

 "\n" + obj.CompanyName +

 "\n" + obj.DoorNo + ", " + obj.Street +

 "\n" + obj.City + 

     "\n" + obj.Country;

MessageBox.Show(strMsg);



string strAuthor=ConfigurationSettings.AppSettings["author"];

MessageBox.Show("This sample is coded by " + strAuthor);



.NET 2.0... 






posted by 방랑군 2009. 9. 23. 14:19

Using Alternative Configuration Sources

You can also use any XML configuration file or other source of configuration information if required. For example, you can load configuration information into containers from a specific named configuration file by using the .NET Framework System.Configuration.Configuration class to retrieve the information from any XML formatted file. The following code shows how you can read configuration information from a file named MyConfig.config.


클래스 ExeConfigurationFileMap 

namespace System.Configuration

{

    // 요약:

    //     Exe.config 파일의 구성 파일 매핑을 정의합니다. 이 클래스는 상속될 수 없습니다.

    public sealed class ExeConfigurationFileMap : ConfigurationFileMap


참조 : Unity Application Block 1.2 - October 2008 Configuring Containers at Design Time

ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = "MyConfig.config";
System.Configuration.Configuration config 
  = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); 
UnityConfigurationSection section
  = (UnityConfigurationSection)config.GetSection("unity");
IUnityContainer container = new UnityContainer();
section.Containers["myContainer"].Configure(container);


- Unity Application Block 에서 사용 소스..

 private SysConfiguration OpenConfigFile(string baseName)

        {

            ExeConfigurationFileMap map = new ExeConfigurationFileMap();

            map.ExeConfigFilename = baseName + ".config";

            return ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

        }





posted by 방랑군 2009. 9. 23. 14:12


[Format of the Unity Configuration File]

  <configSections>

    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />

  </configSections>

- UnityConfigurationSection 클래스에 맞는 Config 구성

UnityConfigurationSection section = ConfigurationManager.GetSection("unity") as UnityConfigurationSection;

UnityConfigurationSection 에 매핑해서 활용

    public class UnityConfigurationSection : ConfigurationSection

    {

.

.

ConfigurationSection 이걸 상속함으로써 :IConfigurationSectionHandler 역활 대신한다.
ConfigurationSection 안에 UNITY 만의 구성된 포맷이 정의 되어 있는거 같음...



posted by 방랑군 2009. 9. 23. 13:45


An error occurred creating the configuration section handler for xx 에러 관련

예)
An error occurred creating the configuration section handler for unity: Could not load file or assembly 'Microsoft.Practices.Unity.Configuration' or one of its dependencies. The system cannot find the file specified. (F:\#Document#\[[SPRING.NET]]\[TEMPLETE]\Console_Plural_Genenic\Console_Config\bin\Debug\Console_Config.vshost.exe.Config line 5)

--> 어셈블 등록된 DLL을 못찾아 로딩이 안되어 생긴 문제.
   : 로컬복사를 TRUE로 해서 컴파일 위치에서 하면 된다.
     그리고, FALSE 하면 어셈블 등록된 DLL로 연결된다.


1. 위 예 처럼 Config 의 type 에 선언된 클래스가 로딩이 안된 경우....
   파일 위치를 로컬복사 하던지 어셈블 매핑을 확인한다(어떻게?? ㅋㅋ).


2. 위 1번 빼고 에러메세지 자세히 보면 해결돤다..
    1번도 메세지 보고 가능한데 생각의 전환이 안되 찾지 못한다.. ㅋㅋㅋ
posted by 방랑군 2009. 9. 23. 13:43

 로컬파일에 존재하는 건 제대로 casting 되었는데,
강한 어셈블 DLL 로딩하면 에러가 안나고 "System.Configuration.DefaultSection" 로 CASTING 된다. 
  - 원래 안되었는데 로컬파일 된다음 하니 물려서 된다. 니미(--;)~~.. 근데 잘못 CASTING 된다...
    원래 System.Configuration.DefaultSection 에 매핑되는건지 아님 에러가 나는지 
"Microsoft.Practices.Unity.Configuration.UnityConfigurationSection" 에 CASTING
되는지 확인해보야 하나 그럼 엄청난 삽질과 재설치 테스트를 해야한다.. 그래서, 패스~


  <configSections>

//1) 실행파일 로컬에 존재 해야 함(본인 실행파일이나 DLL)

    <section name="unity2" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />

  </configSections>


//2) 어셈블리에 등록된 DLL 를 호출하는 경우

  <configSections>

    <section name="unity"

              type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,

                 Microsoft.Practices.Unity.Configuration, =1.3.0.0,

                 Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

  </configSections>

.

.

.

  

</configuration>



            Configuration currentConfig =                ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            object config = currentConfig.GetSection("unity2");


            Configuration currentConfig =                ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            object config = currentConfig.GetSection("unity");



'GET > Configuration' 카테고리의 다른 글

사용자가 임의로 만든 any XML configuration file 제어  (1) 2009.09.23
Unity Application Block 에서의 Configuration  (1) 2009.09.23
Error 처리  (0) 2009.09.23
Sample - 1  (0) 2009.09.23
XML Config 제어하기.  (0) 2009.09.23
posted by 방랑군 2009. 9. 23. 13:07




App.config

<?xml version="1.0" encoding="utf-8" ?>

<configuration>


  <configSections>

    <section name="unity" type="Console_Config_User.UserInfo,Console_Config_User" />

  </configSections>


  <unity>

    <NAME>황승재</NAME>

    <ADDRESS>염창동</ADDRESS>

    <HP>016-647-0678</HP>

  </unity>

</configuration>


Console_Config_User.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;


using System.Configuration;


namespace Console_Config_User

{

    class UserInfo : System.Configuration.IConfigurationSectionHandler

    {


        public string _NAME;

        public string _ADDRESS;

        public string _HP;


        public UserInfo()

        {

            _NAME =

            _ADDRESS =

            _HP = "";

            

        }


        #region IConfigurationSectionHandler 멤버


        public object Create(object parent, object configContext, System.Xml.XmlNode section)

        {

            //throw new NotImplementedException();


            UserInfo obj = new UserInfo();


            ///

            /// section.SelectSingleNode("config").InnerText;

            ///

            obj._NAME    = section.SelectSingleNode("NAME").InnerText; // section 이용하여 config 값 넣는다.  

            obj._ADDRESS = section.SelectSingleNode("ADDRESS").InnerText; // section 이용하여 config 값 넣는다.

            obj._HP      = section.SelectSingleNode("HP").InnerText; // section 이용하여 config 값 넣는다.

            return obj;

        }


        #endregion

    }

}


- object parent, object configContext 이거 null 로 들어옴... 


Program.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;


using System.Configuration;


namespace Console_Config_User

{

    class Program

    {

        static void Main(string[] args)

        {


            //object config = ConfigurationManager.GetSection("unity");


            UserInfo container = new UserInfo();

            container = (UserInfo)ConfigurationManager.GetSection("unity");

            

        }

    }

}




posted by 방랑군 2009. 9. 23. 12:46

0. .NET 1.1 ConfigurationSettings.GetConfig("") 와 IConfigurationSectionHandler
    .NET 2.0 ConfigurationManager.GetSection("") 와 IConfigurationSectionHandler

1. App.config, Web.config. machine.config 등 정해진 Config 제어

2. 사용자가 임의로 만든 any XML configuration file 제어

3. Unity Application Block 에서의 Configuration

'GET > Configuration' 카테고리의 다른 글

사용자가 임의로 만든 any XML configuration file 제어  (1) 2009.09.23
Unity Application Block 에서의 Configuration  (1) 2009.09.23
Error 처리  (0) 2009.09.23
Config 의 type 과 DLL 과 연결 관련...  (0) 2009.09.23
Sample - 1  (0) 2009.09.23