잊지 않겠습니다.

NHibernate에서 상속된 model을 지원하는 방법은 총 3가지가 있다.

1. "subclass" 로 하나의 Table에 discriminator column을 지정해서 생성하는 방법
  - discriminator 값으로는 class의 full name이 들어가게 된다.
2. "joined-subclass"로 model의 parent class를 하나의 Table로, 그리고 나머지 model의 property를 묶은 table을 FK로 엮는 방법
3. "union-subclass"로 정규화를 고려하지 않고, 상속된 모든 property를 각각의 table로 구현하는 방법


subclass




  
    
      
    
        
        
    
    
  
  
    
    
    
  
    
  



joined-subclass




  
    
      
    
        
    
    
  
  
    
    
    
  
  
    
        
  


union-subclass




  
    
      
    
        
    
    
  
      
    
    
  
  
        
  


저작자 표시 비영리 변경 금지
신고
Posted by xyzlast Y2K
RSAServiceProvider를 이용해서 xml 파일에 서명 및 Decryption 하는 과정
RSAServiceProvider를 제공된 public key를 이용해서 얻어내는 것이 이 코드의 핵심.



private String publicOnlyKey;
private void btnSign_Click(object sender, EventArgs e)
{
    try
    {
        /////////////////////////////////////////////////////////////////
        // Create a new RSA signing key and export public key for 
        // verification.
        
        RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider();
        
        //Public Key exported
        //Public Key 뿐 아니라 Private Key도 얻어내는 것이 가능하다. 사용자에게 Key를 보내거나 저장할 때 이용 가능
        publicOnlyKey = rsaKey.ToXmlString(false);
        tbxRSAParameters.Text = publicOnlyKey;
        
        /////////////////////////////////////////////////////////////////
        // Sign the XML document.
        // 

        SignXml(xmlDoc, rsaKey);
        MessageBox.Show("XML file signed.");


        /////////////////////////////////////////////////////////////////
        // Save and display the signed document.
        // 

        xmlDoc.Save("test1.xml");
        tbxDigitalSignature.Text = xmlDoc.OuterXml;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

///XML파일을 RSA를 이용해서 서명. SignedXml class가 있는 것을 기억하고 있을것!
public static void SignXml(XmlDocument Doc, RSA Key)
{
    // Check arguments.
    if (Doc == null)
        throw new ArgumentException("Doc");
    if (Key == null)
        throw new ArgumentException("Key");

    try
    {
        // Create a SignedXml object to generate signature.
        SignedXml signedXml = new SignedXml(Doc);

        // Add the key to the SignedXml document
        signedXml.SigningKey = Key;

        // Create a reference to be signed
        Reference reference = new Reference();
        reference.Uri = "";

        // Add an enveloped transformation to the reference
        XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
        reference.AddTransform(env);

        // Add the reference to the SignedXml object
        signedXml.AddReference(reference);

        // Compute the signature
        signedXml.ComputeSignature();

        // Get the XML representation of the signature and save
        // it to an XmlElement object.
        XmlElement xmlDigitalSignature = signedXml.GetXml();

        // Append the element to the XML document.
        Doc.DocumentElement.AppendChild(Doc.ImportNode(xmlDigitalSignature, true));
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

private void btnVerify_Click(object sender, EventArgs e)
{
    /////////////////////////////////////////////////////////////////////
    // Create a new RSA signing key and import public key for 
    // verification.
    //

    //NOTE:Public RSA Key를 이용해서 RSACryptoService Generate
    RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider();
    rsaKey.FromXmlString(publicOnlyKey);
    /////////////////////////////////////////////////////////////////////
    // Load the signed XML, and call VerifyXml to verify the signature of 
    // the signed XML.
    // 

    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load("test1.xml");

    bool result = VerifyXml(xmlDoc, rsaKey);

    if (result)
    {
        MessageBox.Show("The XML signature is valid.");
    }
    else
    {
        MessageBox.Show("The XML signature is not valid.");
    }
}

public static Boolean VerifyXml(XmlDocument Doc, RSA Key)
{
    // Check arguments.
    if (Doc == null)
        throw new ArgumentException("Doc");
    if (Key == null)
        throw new ArgumentException("Key");


    /////////////////////////////////////////////////////////////////////
    // Create a SignedXml object to verify the signature
    //

    SignedXml signedXml = new SignedXml(Doc);

    // Find Signature node and create a new XmlNodeList object
    XmlNodeList nodeList = Doc.GetElementsByTagName("Signature");

    // Throw an exception if no signature was found.
    if (nodeList.Count <= 0)
    {
        throw new CryptographicException(
            "Verification failed:" +
            " No Signature was found in the document.");
    }

    // This example only supports one signature for entire XML document
    if (nodeList.Count >= 2)
    {
        throw new CryptographicException(
            "Verification failed: More that one signature was found.");
    }

    // Load the first  node.  
    signedXml.LoadXml((XmlElement)nodeList[0]);

    // Check the signature and return the result.
    return signedXml.CheckSignature(Key);
}

private void btnChangeXML_Click(object sender, EventArgs e)
{
    // Modify the value of the Xml document for test. 

    XDocument xDoc = XDocument.Load("test1.xml");

    if (xDoc != null)
    {
        xDoc.Element("invoice").Element("items").
            Element("creditcard").Element("number").SetValue("19834210");

        xDoc.Save("test1.xml");

        tbxModifiedMessage.Text = xDoc.ToString();
    }
}
저작자 표시 비영리 변경 금지
신고
Posted by xyzlast Y2K

0004. XmlGeneral

Sample Codes 2010.01.05 13:21
xml파일을 각 ElementNode별로 읽고, XmlDocument를 생성하고 저장하는 sample code
XmlDocument에 새로운 Element를 생성하는 것은 생성후에 XmlDocument에 넣는 것이 아니라, XmlDocument를 통해 객체를
생성하고, 생성된 객체에 값을 넣은 이후에 XmlDocument에 Append하는 과정을 거쳐야지 된다는 것을 기억하면 매우 쉬운 소스다.


/****************************** Module Header ******************************\
* Module Name:	Program.cs
* Project:		CSXmlGeneral
* Copyright (c) Microsoft Corporation.
* 
* This C# sample project shows how to read a XML file by using XmlTextReader 
* or XmlNodeReader. It also shows, instead of using forward-only reader, how 
* to read, modify, and update Xml element using the XmlDocument class. This 
* class will load the whole document into memory for modification and we can 
* save the modified XML file to the file system.
* 
* The XML file used by the demo has this format:
* 
* 
*  
*    Gambardella, Matthew
*    XML Developer's Guide
*    Computer
*    44.95
*    2000-10-01
*    
*      An in-depth look at creating applications
*      with XML.
*    
*  
*  
*   ...
*  
* 
* 
* This source is subject to the Microsoft Public License.
* See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
* All other rights reserved.
* 
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
\***************************************************************************/

#region Using directives
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
#endregion


class Program
{
    static void Main(string[] args)
    {
        /////////////////////////////////////////////////////////////////////
        // Read XML document using the XmlTextReader class.
        // 

        // The XmlTextReader acts as a reader pointer that only moves forward.
        // Because it always moves forward and read a piece of data into 
        // memory buffer, it has better performance than the XmlDocument 
        // class which loads the whole document into memory.

        Console.WriteLine("Loading XML using XmlTextReader...");

        XmlTextReader xmlTextReader = new XmlTextReader(@"Books.xml");
        xmlTextReader.WhitespaceHandling = WhitespaceHandling.None;

        while (xmlTextReader.Read())
        {
            if (xmlTextReader.Name == "book")
            {
                Console.WriteLine(xmlTextReader.GetAttribute("id") + ": ");

                xmlTextReader.Read();
                string author = xmlTextReader.ReadElementContentAsString();
                string title = xmlTextReader.ReadElementContentAsString();
                string genre = xmlTextReader.ReadElementContentAsString();
                string price = xmlTextReader.ReadElementContentAsString();
                string publishDate = xmlTextReader.ReadElementContentAsString();
                string description = xmlTextReader.ReadElementContentAsString();

                Console.WriteLine(genre + " book \"" + title + "\" written by \"" +
                    author + "\", published on " + publishDate);
                Console.WriteLine(description);
            }
        }

        xmlTextReader.Close();


        /////////////////////////////////////////////////////////////////////
        // Read XML document using the XmlDocument and XmlNodeReader classes.
        // 

        // XmlNodeReader is similar to XmlTextReader but accepts an XmlNode 
        // instance as target to read. The following code shows how to use 
        // XmlDocument and XmlNodeReader to retrieve XML information. It is 
        // also a forward-only reader.

        Console.WriteLine("Loading XML using XmlDocument & XmlNodeReader...");

        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.Load(@"Books.xml");
        XmlNodeList xmlNodes = xmlDocument.GetElementsByTagName("book");
        foreach (XmlNode node in xmlNodes)
        {
            Console.WriteLine(node.Attributes["id"].Value + ":");

            XmlNodeReader xmlNodeReader = new XmlNodeReader(node);
            xmlNodeReader.Read();
            xmlNodeReader.Read();
            string author = xmlNodeReader.ReadElementContentAsString();
            string title = xmlNodeReader.ReadElementContentAsString();
            string genre = xmlNodeReader.ReadElementContentAsString();
            string price = xmlNodeReader.ReadElementContentAsString();
            string publishDate = xmlNodeReader.ReadElementContentAsString();
            string description = xmlNodeReader.ReadElementContentAsString();

            Console.WriteLine(genre + " book \"" + title + "\" written by \"" +
                author + "\", published on " + publishDate);
            Console.WriteLine(description);
        }


        /////////////////////////////////////////////////////////////////////
        // Make changes to the XmlDocument.
        // 

        // Modify a node value by first calling SelectSingleNode to navigate 
        // to that node and by setting its InnerText property to change its 
        // content.
        XmlNode nodeToModify = xmlDocument.DocumentElement.SelectSingleNode(
            "book/genre");
        nodeToModify.InnerText = "XML Tech";

        // Add a new XML node. In XML programming, we always call 
        // XMLDocument.Create*** to create an attribute or element. After 
        // that, we can add it into where we want by calling Node.AppendChild
        XmlElement newElement = xmlDocument.CreateElement("book");
        XmlAttribute newAttribute = xmlDocument.CreateAttribute("id");
        newAttribute.Value = "bk103";
        XmlElement authorElement = xmlDocument.CreateElement("author");
        authorElement.InnerText = "Mark Russinovich,David Solomon,Alex Ionecsu";
        XmlElement titleElement = xmlDocument.CreateElement("title");
        titleElement.InnerText = "Windows Internals, 5th edition";
        XmlElement genreElement = xmlDocument.CreateElement("genre");
        genreElement.InnerText = "Windows Server 2008";
        XmlElement priceElement = xmlDocument.CreateElement("price");
        priceElement.InnerText = "69.99";
        XmlElement publishDateElement = xmlDocument.CreateElement("publish_date");
        publishDateElement.InnerText = "2009-6-17";
        XmlElement descriptionElement = xmlDocument.CreateElement("description");
        descriptionElement.InnerText = "Windows Internals, 5th edition is the" +
            " update to Windows Internals, 4th edition to cover Windows Vista" +
            " and Windows Server 2008 (32-bit and 64-bit).";

        newElement.Attributes.Append(newAttribute);
        newElement.AppendChild(authorElement);
        newElement.AppendChild(titleElement);
        newElement.AppendChild(genreElement);
        newElement.AppendChild(priceElement);
        newElement.AppendChild(publishDateElement);
        newElement.AppendChild(descriptionElement);
        xmlDocument.DocumentElement.AppendChild(newElement);

        // Save the changes
        xmlDocument.Save("Modified Books.xml");

        // XmlLDocument does not have Close or Dispose method because it is 
        // an in-memory representation of an XML document. Once read, the 
        // file is no-longer needed.
    }
}



  
    Gambardella, Matthew
    XML Developer's Guide
    Computer
    44.95
    2000-10-01
    
      An in-depth look at creating applications
      with XML.
    
  
  
    Ralls, Kim
    Midnight Rain
    Fantasy
    5.95
    2000-12-16
    
      A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.
    
  

저작자 표시 비영리 변경 금지
신고
Posted by xyzlast Y2K
.NET에서 Serialization은 객체를 저장하고, 객체를 다시 불러오는데 매우 유용하다. 그리고 네트워크로 Serialization된 객체를 전송하고,
다시 그 객체를 사용할 수 도 있는 .NET에서 핵심적인 기능중 하나이다.

XmlSerialization을 하기 위해 가장 유의할 점은 생성자는 input parameter가 없는 생성자만이 가능하다는 점을 항시 알아야지 된다.
input parameter가 있는 경우에는 Runtime시에 exception이 발생되게 된다.


/****************************** Module Header ******************************\
* Module Name:	Program.cs
* Project:		CSXmlSerialization
* Copyright (c) Microsoft Corporation.
* 
* This sample shows how to serialize an in-memory object to a local xml file 
* and how to deserialize the xml file back to an in-memory object using 
* C#. The designed MySerializableType includes int, string, generic, as well
* as customized type field and property.
* 
* This source is subject to the Microsoft Public License.
* See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
* All other rights reserved.
* 
* History:
* * 7/29/2009 3:00 PM Colbert Zhou Created
* * 8/20/2009 12:01 AM Jialiang Ge Reviewed
\***************************************************************************/

#region Using directives
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Collections;
#endregion


namespace CSXmlSerialization
{
    class Program
    {
        static void Main(string[] args)
        {
            /////////////////////////////////////////////////////////////////
            // Serialize the object to an XML file.
            // 

            // Create and initialize a MySerializableType instance.
            MySerializableType instance = new MySerializableType();
            instance.BoolValue = true;
            instance.IntValue = 1;
            instance.StringValue = "Test String";
            instance.ListValue.Add("List Item 1");
            instance.ListValue.Add("List Item 2");
            instance.ListValue.Add("List Item 3");
            instance.AnotherTypeValue = new AnotherType();
            instance.AnotherTypeValue.IntValue = 2;
            instance.AnotherTypeValue.StringValue = "Inner Test String";

            // Create the serializer
            XmlSerializer serializer = new XmlSerializer(typeof(MySerializableType));

            // Serialize the object to an XML file
            using (StreamWriter streamWriter = File.CreateText(
                "CSXmlSerialization.xml"))
            {
                serializer.Serialize(streamWriter, instance);
            }


            /////////////////////////////////////////////////////////////////
            // Deserialize from a XML file to an object instance.
            // 

            // Deserialize the object
            MySerializableType deserializedInstance;
            using (StreamReader streamReader = File.OpenText(
                "CSXmlSerialization.xml"))
            {
                deserializedInstance = serializer.Deserialize(streamReader) 
                    as MySerializableType;
            }

            // Dump the object
            Console.WriteLine("BoolValue: {0}", deserializedInstance.BoolValue);
            Console.WriteLine("IntValue: {0}", deserializedInstance.IntValue);
            Console.WriteLine("StringValue: {0}", deserializedInstance.StringValue);
            Console.WriteLine("AnotherTypeValue.IntValue: {0}", 
                deserializedInstance.AnotherTypeValue.IntValue);
            Console.WriteLine("AnotherTypeValue.StringValue: {0}", 
                deserializedInstance.AnotherTypeValue.StringValue);
            Console.WriteLine("ListValue: ");
            foreach (object obj in deserializedInstance.ListValue)
            {
                Console.WriteLine(obj.ToString());
            }
        }
    }


    /// 
    /// Serializable Type Declaration
    /// 
    [Serializable()]
    public class MySerializableType
    {
        // String field and property
        private string stringValue;
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }

        // Bool field and property
        private bool boolValue;
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        // Int field and property
        private int intValue;
        public int IntValue
        {
            get { return intValue; }
            set { intValue = value; }
        }

        // Another type field and property
        private AnotherType anotherTypeValue;
        public AnotherType AnotherTypeValue
        {
            get { return anotherTypeValue; }
            set { anotherTypeValue = value; }
        }

        // Generic type field and property
        private List listValue = new List();
        public List ListValue
        {
            get { return listValue; }
            set { listValue = value; }
        }

        // Ignore a field using NonSerialized attribute
        [NonSerialized()]
        private int ignoredField = 1;
    }

    /// 
    /// Another Type Declaration
    /// 
    [Serializable()]
    public class AnotherType
    {
        private string stringValue;
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }

        private int intValue;
        public int IntValue
        {
            get { return intValue; }
            set { intValue = value; }
        }
    }
}
저작자 표시 비영리 변경 금지
신고
Posted by xyzlast Y2K

0002. CSXPath

Sample Codes 2010.01.05 13:10
XPathNavigator를 이용해서 Xml 문서를 탐색하고 값을 얻어내는 예제.
특별히 설명될 내용이 없는 간단한 예제이다.

조금 눈 여겨 볼 내용은 XmlDocument를 통해서 생성되는 것이 아닌 XPathDocument를 통해서 XPathNavigator를 생성한다는 점이다.
단순하게 문서를 읽는데에는 XmlDocument나 XDocument를 사용하는 것이 좋으나, xml 파일이 커지거나 xml파일을 일정하게 검색, 변경
할때에는 XPathNavigator를 통해서 검색하는 것이 속도나 코드 면에서 훨씬 좋다.


/****************************** Module Header ******************************\
* Module Name:	Program.cs
* Project:		CSXPath
* Copyright (c) Microsoft Corporation.
* 
* This sample project shows how to use XPathDocument class to load the XML 
* file and manipulate. It includes two main parts, XPathNavigator usage and 
* XPath Expression usage. The first part shows how to use XPathNavigator to 
* navigate through the whole document, read its content. The second part 
* shows how to use XPath expression to filter information and select it out.
* 
* This source is subject to the Microsoft Public License.
* See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
* All other rights reserved.
* 
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
\***************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;


namespace CSXPath
{
    class Program
    {
        static void Main(string[] args)
        {
            #region Initialize XPathDocument and XPathNavigator

            XPathNavigator xPathNavigator;
            XPathDocument xPathDoc;
            
            //Navigate through the whole document
            //Create a new instance of XPathDocument from a XML file
            xPathDoc = new XPathDocument("books.xml");

            //Call CreateNavigator method to create a navigator instance
            //And we will use this navigator object to navigate through whole document
            xPathNavigator = xPathDoc.CreateNavigator();
            
            #endregion

            #region Navigate through the document

            //Move to the root element
            xPathNavigator.MoveToRoot();
            //Catalog element is the first children of the root
            //Move to catalog element
            xPathNavigator.MoveToFirstChild();
            //We can know a XML node's type from the NodeType property
            //XPathNodeType has Attribute, Element, Namespace and so on
            if (xPathNavigator.NodeType == XPathNodeType.Element)
            {
                //We can know if a Node has child nodes by checking its
                //HasChildren property. If it returns true, that node has
                //child nodes
                if (xPathNavigator.HasChildren == true)
                {
                    //Move to the first child which is our first book nodes
                    xPathNavigator.MoveToFirstChild();
                    do
                    {
                        //We can know if a node has any attribute by checking
                        //the HasAttributes property. When this property returns
                        //true, we can get the specified attribute by calling
                        //navigator.GetAttribute() method
                        if (xPathNavigator.HasAttributes == true)
                        {
                            Console.WriteLine("Book ID: " + xPathNavigator.GetAttribute("id", ""));
                        }

                        //Iterate through a book node's child nodes
                        //and list all child node information, like 
                        //name, author, price, publish date and so on
                        if (xPathNavigator.HasChildren)
                        {
                            xPathNavigator.MoveToFirstChild();
                            do
                            {
                                Console.Write("\t{0}:\t{1}\r\n", xPathNavigator.Name, xPathNavigator.Value);
                            } while (xPathNavigator.MoveToNext());
                            //When all child nodes are reached. The MoveToNext() method returns
                            //false. Then we need to call MoveToParent to go back to the book level
                            xPathNavigator.MoveToParent();
                        }
                        //Move to the next book element.
                    } while (xPathNavigator.MoveToNext());
                }
            }

            #endregion

            #region Use of XPath Expression
            
            //Use XPath Expression to select out book bk103
            //The expression should be "/catalog/book[@id='bk103']"
            //@ means to look id attribute and match bk103
            Console.WriteLine("Use XPath Expression to select out the book with ID bk103:");
            XPathExpression expression = xPathNavigator.Compile("/catalog/book[@id='bk103']");
            XPathNodeIterator iterator = xPathNavigator.Select(expression);

            //After compile the XPath expression, we can call navigator.Select
            //to retrieve the XPathNodeIterator. With this interator, we can loop
            //trough the results filtered by the XPath expression
            //The following codes print the book bk103's detailed information
            
            while (iterator.MoveNext())
            {
                XPathNavigator nav = iterator.Current.Clone();
                Console.WriteLine("Book ID: " + nav.GetAttribute("id", ""));
                if (nav.HasChildren)
                {
                    nav.MoveToFirstChild();
                    do
                    {
                        Console.Write("\t{0}:\t{1}\r\n", nav.Name, nav.Value);
                    } while (nav.MoveToNext());
                }
            }


            //Use XPath to select out all books whose price are more than 10.00
            // '[]' means to look into the child node to match the condition "price > 10"
            Console.WriteLine("\r\nUse XPath Expression to select out all books whose price are more than 10:");
            expression = xPathNavigator.Compile("/catalog/book[price>10]");
            iterator = xPathNavigator.Select(expression);

            //After getting the iterator, we print title and price for books 
            //whose price are more than 10
            while (iterator.MoveNext())
            {
                XPathNavigator nav = iterator.Current.Clone();
                Console.WriteLine("Book ID: " + nav.GetAttribute("id", ""));
                if (nav.HasChildren)
                {
                    nav.MoveToFirstChild();
                    do
                    {
                        if (nav.Name == "title")
                        {
                            Console.Write("\t{0}:\t{1}\r\n", nav.Name, nav.Value);
                        }
                        if (nav.Name == "price")
                        {
                            Console.Write("\t{0}:\t{1}\r\n", nav.Name, nav.Value);
                        }
                    } while (nav.MoveToNext());
                }
            }

            //Use XPath Expression to calculate the average price of all books.
            //Here in XPath, we use the sum, div, and count formula.
            Console.WriteLine("\r\nUse XPath Expression to calculate the average price of all books:");
            expression = xPathNavigator.Compile("sum(/catalog/book/price) div count(/catalog/book/price)");
            string averagePrice = xPathNavigator.Evaluate(expression).ToString();
            Console.WriteLine("The average price of the books are {0}", averagePrice);


            #endregion

            #region End. Read a char to exit

            Console.WriteLine("Input any key to quit the sample application");
            Console.ReadLine();

            #endregion
        }
    }
}



  
    Gambardella, Matthew
    XML Developer's Guide
    Computer
    44.95
    2000-10-01
    
      An in-depth look at creating applications
      with XML.
    
  
  
    Ralls, Kim
    Midnight Rain
    Fantasy
    5.95
    2000-12-16
    
      A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.
    
  
  
    Corets, Eva
    Maeve Ascendant
    Fantasy
    5.95
    2000-11-17
    
      After the collapse of a nanotechnology
      society in England, the young survivors lay the
      foundation for a new society.
    
  
  
    Corets, Eva
    Oberon's Legacy
    Fantasy
    5.95
    2001-03-10
    
      In post-apocalypse England, the mysterious
      agent known only as Oberon helps to create a new life
      for the inhabitants of London. Sequel to Maeve
      Ascendant.
    
  
  
    Corets, Eva
    The Sundered Grail
    Fantasy
    5.95
    2001-09-10
    
      The two daughters of Maeve, half-sisters,
      battle one another for control of England. Sequel to
      Oberon's Legacy.
    
  
  
    Randall, Cynthia
    Lover Birds
    Romance
    4.95
    2000-09-02
    
      When Carla meets Paul at an ornithology
      conference, tempers fly as feathers get ruffled.
    
  
  
    Thurman, Paula
    Splish Splash
    Romance
    4.95
    2000-11-02
    
      A deep sea diver finds true love twenty
      thousand leagues beneath the sea.
    
  
  
    Knorr, Stefan
    Creepy Crawlies
    Horror
    4.95
    2000-12-06
    
      An anthology of horror stories about roaches,
      centipedes, scorpions  and other insects.
    
  
  
    Kress, Peter
    Paradox Lost
    Science Fiction
    6.95
    2000-11-02
    
      After an inadvertant trip through a Heisenberg
      Uncertainty Device, James Salway discovers the problems
      of being quantum.
    
  
  
    O'Brien, Tim
    Microsoft .NET: The Programming Bible
    Computer
    36.95
    2000-12-09
    
      Microsoft's .NET initiative is explored in
      detail in this deep programmer's reference.
    
  
  
    O'Brien, Tim
    MSXML3: A Comprehensive Guide
    Computer
    36.95
    2000-12-01
    
      The Microsoft MSXML3 parser is covered in
      detail, with attention to XML DOM interfaces, XSLT processing,
      SAX and more.
    
  
  
    Galos, Mike
    Visual Studio 7: A Comprehensive Guide
    Computer
    49.95
    2001-04-16
    
      Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are
      integrated into a comprehensive development
      environment.
    
  

저작자 표시 비영리 변경 금지
신고
Posted by xyzlast Y2K
CodePlex에서 진행되고 있는 All-In-One Code Framework 소개 (http://cfx.codeplex.com/wikipage?title=All-In-One%20Code%20Framework%20Examples&ProjectName=cfx)

xml파일을 xsl 형식을 이용해서 converting 하는 예제코드.
System.Xml.Xsl.XslCompiledTransform를 이용해서 converting 하는 간단한 예제를 보이고 있다.


 


  
    Gambardella Matthew
    XML Developer's Guide
    Computer
    44.95
    2000-10-01
    An in-depth look at creating applications with XML.
  
  
    Ralls Kim
    Midnight Rain
    Fantasy
    5.95
    2000-12-16
    A former architect battles corporate zombies and her own childhood to become queen of the world.
  
  
    Corets Eva
    Maeve Ascendant
    Fantasy
    5.95
    2000-11-17
    After the collapse of a nanotechnology society in England the young survivors lay the foundation for a new society.
  
  
    Corets Eva
    Oberon's Legacy
    Fantasy
    5.95
    2001-03-10
    In post-apocalypse England the mysterious agent known only as Oberon helps to create a new life for the inhabitants of London. Sequel to Maeve Ascendant.
  
  
    Corets Eva
    The Sundered Grail
    Fantasy
    5.95
    2001-09-10
    The two daughters of Maeve half-sisters battle one another for control of England. Sequel to Oberon's Legacy.
  
  
    Randall Cynthia
    Lover Birds
    Romance
    4.95
    2000-09-02
    When Carla meets Paul at an ornithology conference tempers fly as feathers get ruffled.
  
  
    Thurman Paula
    Splish Splash
    Romance
    4.95
    2000-11-02
    A deep sea diver finds true love twenty thousand leagues beneath the sea.
  
  
    Knorr Stefan
    Creepy Crawlies
    Horror
    4.95
    2000-12-06
    An anthology of horror stories about roaches centipedes scorpions  and other insects.
  
  
    Kress Peter
    Paradox Lost
    Science Fiction
    6.95
    2000-11-02
    After an inadvertant trip through a Heisenberg Uncertainty Device James Salway discovers the problems of being quantum.
  
  
    O'Brien Tim
    Microsoft .NET: The Programming Bible
    Computer
    36.95
    2000-12-09
    Microsoft's .NET initiative is explored in detail in this deep programmer's reference.
  
  
    O'Brien Tim
    MSXML3: A Comprehensive Guide
    Computer
    36.95
    2000-12-01
    The Microsoft MSXML3 parser is covered in detail with attention to XML DOM interfaces XSLT processing SAX and more.
  
  
    Galos Mike
    Visual Studio 7: A Comprehensive Guide
    Computer
    49.95
    2001-04-16
    Microsoft Visual Studio 7 is explored in depth looking at how Visual Basic/Visual C++/C#/ASP+ are integrated into a comprehensive development environment.
  



    
    
      
    
    
      "
      
      "
      
      
        "
        
        "
        
          
        
      
      


    


#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Xsl;
#endregion


namespace CSXslTransformXml
{
    class Program
    {
        static void Main(string[] args)
        {
            XslCompiledTransform transform = new XslCompiledTransform();
            transform.Load("Books.xslt");
            transform.Transform("Books.xml", "Books.csv");
        }
    }
}
저작자 표시 비영리 변경 금지
신고
Posted by xyzlast Y2K

Pro LINQ (07)

Book 2009.01.15 02:32
XML Schema(*.xsd)파일을 이용한 XML의 Validation과 기존의 XmlDocument에서 지원되는 XPath 역시 같이 지원 가능하다. 또한, 제공되는 XML을 통한 XML Schema를 역으로 얻어내는 방법을 같이 제공하고 있다. 

var xDocument = new XDocument();
var rootElement = new XElement("BookParticipants");

var bookElement1 = new XElement("BookParticipant");
bookElement1.Add(new XAttribute("type", "Author"));
bookElement1.Add(new XElement("FirstName", "Joe"));
bookElement1.Add(new XElement("LastName", "Rattz"));
rootElement.Add(bookElement1);

var bookElement2 = new XElement("BookParticipant");
bookElement2.Add(new XAttribute("type", "Editor"));
bookElement2.Add(new XElement("FirstName", "Ewan"));
bookElement2.Add(new XElement("LastName", "Buckingham"));
rootElement.Add(bookElement2);

xDocument.Add(rootElement);
xDocument.Save("bookparticipants.xml");

XmlSchemaInference infer = new XmlSchemaInference();
XmlSchemaSet schemaSet = infer.InferSchema(XmlReader.Create("bookparticipants.xml"));
XmlWriter xmlWriter = XmlWriter.Create("bookparticipants.xsd");

foreach(XmlSchema xmlSchema in schemaSet.Schemas())
{
    xmlSchema.Write(xmlWriter);
}
xmlWriter.Close();

XDocument schemaDocument = XDocument.Load("bookparticipants.xsd");
Console.WriteLine(schemaDocument);

정말로 대단한 기능이라고 생각이 되는 것이, XML 파일만 있더라고 그 안에서 XSD의 추론이 가능해지기 때문에, 그 응용을 어떤 방향으로 솔찍히 해줘야지 될지 잘은 모르겠다는 생각이 든다. 아직 XSD를 잘 사용을 안하고 있는 것이 잘 모르고 있는 이유중 하나일 것 같다.

XML의 Validation은 다음과 같이 할 수 있다. 기존의 XmlDocument와 코드가 완전히 동일하다.
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add(string.Empty, "bookparticipants.xsd");
try
{
    xDocument.Validate(schemaSet, null);
    Console.WriteLine("Document validated successfully");
}
catch(XmlSchemaValidationException ex)
{
    Console.WriteLine(ex.Message);
}


마지막으로 XDocument에서의 XPath 사용을 간략한 예이다.
xDocument.Add(rootElement);
XElement xElement = xDocument.XPathSelectElement("//BookParticipants/BookParticipant[FirstName='Joe']");
Console.WriteLine(string.Format("Selected Element : {0} / {1}", xElement.Name, xElement.Value));




저작자 표시 비영리
신고
Posted by xyzlast Y2K
TAG Linq, Pro LINQ, XML
1. XDocument to XmlDocument
            XDocument xDocument = new XDocument();
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(xDocument.CreateReader());

2. XmlDocument to XDocument
            StringReader sr = new StringReader(xmlDoc.InnerXml);
            XDocument xDocument = XDocument.Load(XmlReader.Create(sr));


저작자 표시 비영리
신고
Posted by xyzlast Y2K
TAG Linq, XML

어제 책을 읽다가 기존에 사용하고 있던 일반적인 text 형태의 Error reporter를 조금 예쁘게 만들어보고 싶다는 생각이 들어서 급조한 소스. 

xslt에 대한 포멧을 아직은 정확히 알지를 못해서 좀더 공부를 해볼 필요가 있을것 같다.
무엇보다 모든 일에 대한 표준화를 제공해줄수 있다는 점에서 가장 큰 장점을 가지고 있는듯. 

Class Source
    using System.Net.Mail;
    using System.Xml;
    using System.Xml.Linq;
    using System.IO;
    using System.Xml.Xsl;

    public class ExceptionReporter
    {
        private readonly Exception reportedException;
        public ExceptionReporter(Exception ex)
        {
            reportedException = ex;
        }

        public string ConvertXml()
        {
            XDocument xDocument = new XDocument();
            XElement rootElement = new XElement("Exceptions");
            XElement element = new XElement("ExceptionInfo");
            
            rootElement.Add(element);
            element.Add(new XElement("ExceptionType", reportedException.GetType().ToString()));
            element.Add(new XElement("Message", reportedException.Message));
            element.Add(new XElement("Source", reportedException.Source));
            element.Add(new XElement("TargetSite", reportedException.TargetSite));
            element.Add(new XElement("StackTrace", reportedException.StackTrace));
            xDocument.Add(rootElement);
            
            string xsl = File.ReadAllText("ErrorReporter.xslt");
            XDocument transformedDoc = new XDocument();
            using(XmlWriter xmlWriter = transformedDoc.CreateWriter())
            {
                XslCompiledTransform transform = new XslCompiledTransform();
                transform.Load(XmlReader.Create(new StringReader(xsl)));
                transform.Transform(xDocument.CreateReader(), xmlWriter);
            }
            return transformedDoc.ToString();
        }

        public bool SendEmailToManager()
        {
            SmtpClient client = new SmtpClient("smtpAddress");
            MailMessage mailMessage = new MailMessage();
            mailMessage.Subject = "Subject";
            mailMessage.IsBodyHtml = true;
            mailMessage.Body = ConvertXml();
            mailMessage.From = new MailAddress("fromMailAddress");
            mailMessage.To.Add(new MailAddress("toMailAddress"));
            client.Send(mailMessage);

            return true;
        }
    }


XSLT File
<?xml version='1.0' encoding='utf-8'?>
<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
  <xsl:output method='html'/>
  <xsl:template match='/'>
    <body>
      <xsl:apply-templates/>
    </body>    
  </xsl:template>

  <xsl:template match='ExceptionInfo'>
    <table width="100%" bgcolor="#d1d9e4" cellspacing="1" cellpadding="3">
      <tr>
        <td bgcolor="#666666" colspan="2">
          <font face="Arial" color="white">
            <b>Error Information</b>
          </font>
        </td>
      </tr>
      <tr bgcolor="#d0d0d0">
        <th>Parameter</th>
        <th>Data</th>
      </tr>
    <xsl:apply-templates />      
    </table>
  </xsl:template>
  <xsl:template match='ExceptionType'>
    <tr valign="top" bgcolor="white">
      <td>Exception Type</td>
      <td><xsl:apply-templates/></td>
    </tr>
  </xsl:template>  
  <xsl:template match='Message'>
    <tr valign="top" bgcolor="#f4f4f4">
      <td>Message</td>
      <td>
        <xsl:apply-templates/>
      </td>
    </tr>
  </xsl:template>
  <xsl:template match='Source'>
    <tr valign="top" bgcolor="white">
      <td>Source</td>
      <td><xsl:apply-templates/></td>
    </tr>
  </xsl:template>
  <xsl:template match="TargetSite">
    <tr valign="top" bgcolor="#f4f4f4">
      <td>TargetSite</td>
      <td><xsl:apply-templates/></td>
    </tr>    
  </xsl:template>
  <xsl:template match="StackTrace">
    <tr valign="top" bgcolor="white">
      <td>Stack Trace</td>
      <td><xsl:apply-imports/></td>
    </tr>
  </xsl:template>
</xsl:stylesheet>


사용 예제 : 
            try
            {
                File.ReadAllText("C:\\afwqerqwer.txt");
            }
            catch(Exception ex)
            {
                ExceptionReporter reporter = new ExceptionReporter(ex);
                reporter.SendEmailToManager();
                //Console.WriteLine(reporter.ConvertXml());
            }


결과:




저작자 표시 비영리
신고
Posted by xyzlast Y2K
TAG XML, XSLT
XElement를 이용하면 XmlDocument를 이용한 XmlDocument의 생성보다 편하고 직관적인 방법을 제공할 수 있다.

XElement - Element 생성
XComment - Comments 생성
XDeclaration - Declaration 생성

    public class XmlLinq2
    {
        public void CreateXmlDocument()
        {
            XNamespace nameSpace = "http://www.hostway.co.kr";
            XElement xBookParticipant = new XElement(nameSpace + "BookParticipant");
            XAttribute bookAttribute = new XAttribute("type", "Author");
            XElement xFirstname = new XElement(nameSpace + "FirstName", "Joe");
            XElement xLastName = new XElement(nameSpace + "LastName", "Rattz");
            XComment xComment = new XComment("This is XComment");

            xBookParticipant.Add(bookAttribute);
            xBookParticipant.Add(xComment);
            xBookParticipant.Add(xFirstname);
            xBookParticipant.Add(xLastName);

            Console.WriteLine(xBookParticipant);
        }

        public void FindDatas()
        {
            XNamespace nameSpace = "http://www.hostway.co.kr";
            XElement xBookParticipant = new XElement(nameSpace + "BookParticipant", 
                                                     new XElement(nameSpace + "FirstName", "Joe"),
                                                     new XElement(nameSpace + "LastName", "Rattz"));
            Console.WriteLine(xBookParticipant.ToString());
            Console.WriteLine(xBookParticipant);
        }
    }

: 기초책을 볼때마다 느끼는 거지만.. 언제나 기본인 내용을 모르고 있는 내 모습이 많이 부끄러워질때가 많은 것 같다. 


저작자 표시
신고
Posted by xyzlast Y2K
TAG c#, XML


티스토리 툴바