잊지 않겠습니다.

wrong javascript in jquery
<div id="mylinks">
    <a href="#" onclick="if(confirm('Follow the link?')) location.href='/someUrl1';">Link1</a>
    <a href="#" onclick="if(confirm('Follow the link?')) location.href='/someUrl2';">Link1</a>
</div>

good javascript in jquery
<div id="mylinks">
    <a href="/someUrl1">Link1</a>
    <a href="/someUrl2">Link2</a>
</div>

<script type="text/javascript">
    $("mylinks a").click(function() {
        return confirm('Floow the links?');
    });
</script>

Javascript를 사용할 때 '튀지 않는' Javascript를 만드는 방법
  * Javascript를 전혀 사용하지 않으면서 응용프로그램이나 기능을 구축해얒 한다. 실행 가능한 기능들을 채택하고 일반적인 HTML/CSS의 한계를 받아드린다.
  * 원 markup을 건드리지 않는 범의 한에서 Javascript를 사용한다. 그리고, 되도록 Javascript를 별도의 파일로 분리하자. 개별적으로 인식이 가능하고, 관리할 수 있는 방법을 제시해야지 된다.

Posted by Y2K
,
.NET으로 COM+ 객체를 만드는 예제.

.NET으로 COM+객체를 만들때는 먼저 Project Property에 Comvisible(true)로 설정이 되어 있어야지 된다. 그리고 assembly:Guid 속성에 component guid를 등록시켜야지만 com 객체를 만드는 가장 기초적인 설정이 끝이 난다. 이와같은 설정을 하면 작성된 dll이나 exe를 com+ 객체로 등록할 수 있다.

1.// Setting ComVisible to false makes the types in this assembly not visible
2.// to COM components.  If you need to access a type in this assembly from
3.// COM, set the ComVisible attribute to true on that type.
4.[assembly: ComVisible(true)]
5.// The following GUID is for the ID of the typelib if this project is exposed to COM
6.[assembly: Guid("3308202e-a355-4c3b-805d-b527d1ef5fa3")]

그러나, dll을 등록한다고해서 library안의 class들이 모두 com객체로 사용할 수 있는 것이 아니다. dll은 여러개의 com객체를 담을 수 있는 상자이고, 그 상자안에 채워야지 될 com객체들은 각각 작성되어야지 된다. com을 이용하는 것은 com 객체 뿐 아니라, com 객체를 구성하고 있는 interface역시 사용할 수 있어야지 되기 때문에, com으로 외부에서 노출될 모든 interface와 class들은 Guid Class Property를 갖고, 각 Guid 값을 가져야지 된다.

com으로 사용되기 위해서, class와 interface가 가져야지 될 속성은 각각 다른데, interface는 ComInterfaceType Property와 Guid를 가져야지 되며, class는 Com으로 제공될 ComSourceInterfaces, ClassInterface, Transaction, Guid, Com 객체 사용에서 Pool과 CreateTimeOut을 제한하는 ObjectPooling attribute를 가져야지 된다.

com interface 구현 예제
01.#region Interfaces
02. 
03.[Description("ICSSimpleObject description")]
04.[Guid("2A59630E-4232-4582-AE47-706E2B648579")]
05.// The public interface describing the COM interface of the coclass
06.public interface ICSSimpleObject
07.{
08.    #region Properties
09. 
10.    float FloatProperty { get; set; }
11. 
12.    #endregion
13. 
14.    #region Methods
15. 
16.    [Description("HelloWorld description")]
17.    string HelloWorld();
18. 
19.    void GetProcessThreadID(out uint processId, out uint threadId);
20. 
21.    [Description("DoTransaction description")]
22.    void DoTransaction();
23. 
24.    #endregion
25.}
26. 
27.[Guid("A06C000A-7A85-42dc-BA6D-BE736B6EB97A")]
28.[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
29.// The public interface describing the events the coclass can sink
30.public interface ICSSimpleObjectEvents
31.{
32.    #region Events
33. 
34.    [DispId(1)]
35.    void FloatPropertyChanging(float NewValue, ref bool Cancel);
36. 
37.    #endregion
38.}
39.#endregion

com class 구현 예제
01.// The ObjectPooling attribute is used to configure the component's object
02.// pooling. It can enable or disables object pooling and set the min. or 
03.// max. pool size and object creation timeout.
04.[ObjectPooling(MinPoolSize=2, MaxPoolSize=10, CreationTimeout=20)]
05.// Creates the component with a new transaction, regardless of the state
06.// of the current context.
07.[Transaction(TransactionOption.Required)]
08.[ClassInterface(ClassInterfaceType.None)]
09.[ComSourceInterfaces(typeof(ICSSimpleObjectEvents))]
10.[Guid("14EAD156-F55E-4d9b-A3C5-658D4BB56D30")]
11.public class CSSimpleObject : ServicedComponent, ICSSimpleObject
12.{
13.    #region Properties
14. 
15.    /// <summary>
16.    /// The private members don't make it into the type-library and are
17.    /// hidden from the COM clients.
18.    /// </summary>
19.    private float fField = 0;
20. 
21.    /// <summary>
22.    /// A public property with both get and set accessor methods.
23.    /// </summary>
24.    public float FloatProperty
25.    {
26.        get { return this.fField; }
27.        set
28.        {
29.            bool cancel = false;
30.            // Raise the event FloatPropertyChanging
31.            if (null != FloatPropertyChanging)
32.                FloatPropertyChanging(value, ref cancel);
33.            if (!cancel)
34.                this.fField = value;
35.        }
36.    }
37. 
38.    #endregion
39. 
40.    #region Methods
41. 
42.    /// <summary>
43.    /// A public method that returns a string "HelloWorld".
44.    /// </summary>
45.    /// <returns>"HelloWorld"</returns>
46.    public string HelloWorld()
47.    {
48.        return "HelloWorld";
49.    }
50. 
51.    /// <summary>
52.    /// A public method with two outputs: the current process Id and the
53.    /// current thread Id.
54.    /// </summary>
55.    /// <param name="processId">[out] The current process Id
56.    /// <param name="threadId">[out] The current thread Id
57.    public void GetProcessThreadID(out uint processId, out uint threadId)
58.    {
59.        processId = NativeMethod.GetCurrentProcessId();
60.        threadId = NativeMethod.GetCurrentThreadId();
61.    }
62. 
63.    public void DoTransaction()
64.    {
65.        try
66.        {
67.            // Operate on the resource managers like DBMS
68.            // ...
69.     
70.            ContextUtil.SetComplete();  // Commit
71.        }
72.        catch (Exception ex)
73.        {
74.            ContextUtil.SetAbort();     // Rollback
75.            throw ex;
76.        }
77.    }
78. 
79.    #endregion
80. 
81.    #region Events
82. 
83.    [ComVisible(false)]
84.    public delegate void FloatPropertyChangingEventHandler(float NewValue, ref bool Cancel);
85. 
86.    /// <summary>
87.    /// A public event that is fired before new value is set to the
88.    /// FloatProperty property. The Cancel parameter allows the client
89.    /// to cancel the change of FloatProperty.
90.    /// </summary>
91.    public event FloatPropertyChangingEventHandler FloatPropertyChanging;
92. 
93.    #endregion
94.}
Posted by Y2K
,
Client 소스는 좀더 간단하다. Server의 경우에는 Bind와 Listen의 절차를 거치고, Listen에서 BeginListen, EndListen으로
AsyncCallback을 통해야지 되지만, Client의 경우에는 간단히 Connect만으로 가능하고, 하나의 Client에서는 역시 하나의
연결정도만 신경을 쓰면 되기 때문에 더욱더 편한 개발이 가능하다.

솔찍한 생각으로 예제 소스이긴 하지만, UI단만 조금 붙여버리면 거의 일반 프로그램들과 큰 차이가 안보인다.
Socket의 Close시에 Shutdown으로 Socket을 정리하는 부분에 신경을 쓰면 될 것 같다.


001./****************************** Module Header ******************************\
002.* Module Name:  Program.cs
003.* Project:      CSSocketClient
004.* Copyright (c) Microsoft Corporation.
005.*
006.* Sockets are an application programming interface(API) in an operating system
007.* used for in inter-process communication. Sockets constitute a mechanism for
008.* delivering incoming data packets to the appropriate application process or
009.* thread, based on a combination of local and remote IP addresses and port
010.* numbers. Each socket is mapped by the operational system to a communicating
011.* application process or thread.
012.*
013.*
014.* .NET supplies a Socket class which implements the Berkeley sockets interface.
015.* It provides a rich set of methods and properties for network communications.
016.* Socket class allows you to perform both synchronous and asynchronous data
017.* transfer using any of the communication protocols listed in the ProtocolType
018.* enumeration. It supplies the following types of socket:
019.*
020.* Stream: Supports reliable, two-way, connection-based byte streams without
021.* the duplication of data and without preservation of boundaries.
022.*
023.* Dgram:Supports datagrams, which are connectionless, unreliable messages of
024.* a fixed (typically small) maximum length.
025.*
026.* Raw: Supports access to the underlying transport protocol.Using the
027.* SocketTypeRaw, you can communicate using protocols like Internet Control
028.* Message Protocol (Icmp) and Internet Group Management Protocol (Igmp).
029.*
030.* Rdm: Supports connectionless, message-oriented, reliably delivered messages,
031.* and preserves message boundaries in data.
032.*
033.* Seqpacket:Provides connection-oriented and reliable two-way transfer of
034.* ordered byte streams across a network.
035.*
036.* Unknown:Specifies an unknown Socket type.
037.*
038.* This source is subject to the Microsoft Public License.
040.* All other rights reserved.
041.*
042.* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
043.* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
044.* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
045.\***************************************************************************/
046. 
047.#region Using directives
048.using System;
049.using System.Collections.Generic;
050.using System.Linq;
051.using System.Text;
052.using System.Net;
053.using System.Net.Sockets;
054.using System.Security;
055.using System.Security.Permissions;
056.#endregion
057. 
058. 
059.public class Program
060.{
061.    static void Main(string[] args)
062.    {
063.        // Receiving byte array
064.        byte[] bytes = new byte[1024];
065.        try
066.        {
067.            // Create one SocketPermission for socket access restrictions
068.            SocketPermission permission = new SocketPermission(
069.                NetworkAccess.Connect,    // Connection permission
070.                TransportType.Tcp,        // Defines transport types
071.                "",                       // Gets the IP addresses
072.                SocketPermission.AllPorts // All ports
073.                );
074. 
075.            // Ensures the code to have permission to access a Socket
076.            permission.Demand();
077. 
078.            // Resolves a host name to an IPHostEntry instance          
079.            IPHostEntry ipHost = Dns.GetHostEntry("");
080. 
081.            // Gets first IP address associated with a localhost
082.            IPAddress ipAddr = ipHost.AddressList[0];
083. 
084.            // Creates a network endpoint
085.            IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 6000);
086. 
087.            // Create one Socket object to setup Tcp connection
088.            Socket sender = new Socket(
089.                ipAddr.AddressFamily,// Specifies the addressing scheme
090.                SocketType.Stream,   // The type of socket
091.                ProtocolType.Tcp     // Specifies the protocols
092.                );
093. 
094.            sender.NoDelay = true;   // Using the Nagle algorithm
095. 
096.            // Establishes a connection to a remote host
097.            sender.Connect(ipEndPoint);
098.            Console.WriteLine("Socket connected to {0}",
099.                sender.RemoteEndPoint.ToString());
100. 
101.            // Sending message
102.            //<client quit=""> is the sign for end of data
103.            string theMessage = "Hello World!";
104.            byte[] msg =
105.                Encoding.Unicode.GetBytes(theMessage +"<client quit="">");
106. 
107.            // Sends data to a connected Socket.
108.            int bytesSend = sender.Send(msg);
109. 
110.            // Receives data from a bound Socket.
111.            int bytesRec = sender.Receive(bytes);
112. 
113.            // Converts byte array to string
114.            theMessage = Encoding.Unicode.GetString(bytes, 0, bytesRec);
115. 
116.            // Continues to read the data till data isn't available
117.            while (sender.Available > 0)
118.            {
119.                bytesRec = sender.Receive(bytes);
120.                theMessage += Encoding.Unicode.GetString(bytes, 0, bytesRec);
121.            }
122.            Console.WriteLine("The server reply: {0}", theMessage);
123. 
124.            // Disables sends and receives on a Socket.
125.            sender.Shutdown(SocketShutdown.Both);
126. 
127.            //Closes the Socket connection and releases all resources
128.            sender.Close();
129.        }
130.        catch (Exception ex)
131.        {
132.            Console.WriteLine("Exception: {0}", ex.ToString());
133.        }
134.    }
135.}
136.</client></client>
Posted by Y2K
,
Socket을 사용해서 TCP/IP 서버를 만들게 되면 개발에서 가장 신경쓰게 되는 것이 Multi-Thread 문제이다.
이부분에 대해서 .NET에서 내놓은 최고의 Solution은 IAsyncCallback interface를 이용해서 BeginXXX 와
EndXXX를 이용하는 방법이다. 이 방법은 WebService client, Stream, Socket 등 데이터를 읽고, 쓰는데에
시간이 소요가 되어 Multi-Thread를 구현해야지 되는 거의 모든 경우에서 사용이 가능하다.

예제 소스는 다음과 같다. IPV6를 사용하는 소스를 IPV4로만 변경시킨 예제이다.


001./****************************** Module Header ******************************\
002.* Module Name:  Program.cs
003.* Project:      CSSocketServer
004.* Copyright (c) Microsoft Corporation.
005.*
006.* Sockets are an application programming interface(API) in an operating system
007.* used for in inter-process communication. Sockets constitute a mechanism for
008.* delivering incoming data packets to the appropriate application process or
009.* thread, based on a combination of local and remote IP addresses and port
010.* numbers. Each socket is mapped by the operational system to a communicating
011.* application process or thread.
012.*
013.*
014.* .NET supplies a Socket class which implements the Berkeley sockets interface.
015.* It provides a rich set of methods and properties for network communications.
016.* Socket class allows you to perform both synchronous and asynchronous data
017.* transfer using any of the communication protocols listed in the ProtocolType
018.* enumeration. It supplies the following types of socket:
019.*
020.* Stream: Supports reliable, two-way, connection-based byte streams without
021.* the duplication of data and without preservation of boundaries.
022.*
023.* Dgram:Supports datagrams, which are connectionless, unreliable messages of
024.* a fixed (typically small) maximum length.
025.*
026.* Raw: Supports access to the underlying transport protocol.Using the
027.* SocketTypeRaw, you can communicate using protocols like Internet Control
028.* Message Protocol (Icmp) and Internet Group Management Protocol (Igmp).
029.*
030.* Rdm: Supports connectionless, message-oriented, reliably delivered messages,
031.* and preserves message boundaries in data.
032.*
033.* Seqpacket:Provides connection-oriented and reliable two-way transfer of
034.* ordered byte streams across a network.
035.*
036.* Unknown:Specifies an unknown Socket type.
037.*
038.* This source is subject to the Microsoft Public License.
040.* All other rights reserved.
041.*
042.* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
043.* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
044.* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
045.\***************************************************************************/
046. 
047.#region Using Directive
048.using System;
049.using System.Collections.Generic;
050.using System.Linq;
051.using System.Text;
052.using System.Net;
053.using System.Net.Sockets;
054.using System.Threading;
055.using System.Security;
056.using System.Security.Permissions;
057.#endregion
058. 
059. 
060.public class Program
061.{
062.    static void Main(string[] args)
063.    {
064.        // Creates one SocketPermission object for access restrictions
065.        SocketPermission permission = new SocketPermission(
066.            NetworkAccess.Accept,     // Allowed to accept connections
067.            TransportType.Tcp,        // Defines transport types
068.            "",                       // The IP addresses of local host
069.            SocketPermission.AllPorts // Specifies all ports
070.            );
071. 
072.        // Listening Socket object
073.        Socket sListener = null;
074. 
075.        try
076.        {
077.            // Ensures the code to have permission to access a Socket
078.            permission.Demand();
079. 
080.            // Resolves a host name to an IPHostEntry instance
081.            IPHostEntry ipHost = Dns.GetHostEntry("");
082. 
083.            ///Get First IPV4 Address
084.            ///아직까지는 IPV4로 만들지 않으면 외부에서 접근을 못하는 경우가 많다.;
085.            IPAddress ipAddr = ipHost.AddressList.Where(a => a.AddressFamily != AddressFamily.InterNetworkV6).First();
086. 
087.            // Creates a network endpoint
088.            IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 6000);
089. 
090.            // Create one Socket object to listen the incoming connection
091.            sListener = new Socket(
092.                ipAddr.AddressFamily,
093.                SocketType.Stream,
094.                ProtocolType.Tcp
095.                );
096. 
097.            // Associates a Socket with a local endpoint
098.            sListener.Bind(ipEndPoint);
099. 
100.            // Places a Socket in a listening state and specifies the maximum
101.            // Length of the pending connections queue
102.            sListener.Listen(10);
103. 
104.            Console.WriteLine("Waiting for a connection on port {0}",
105.                ipEndPoint);
106. 
107.            // Begins an asynchronous operation to accept an attempt
108.            AsyncCallback aCallback = new AsyncCallback(AcceptCallback);
109.            sListener.BeginAccept(aCallback, sListener);
110.        }
111.        catch (Exception ex)
112.        {
113.            Console.WriteLine("Exception: {0}", ex.ToString());
114.            return;
115.        }
116. 
117.        Console.WriteLine("Press the Enter key to exit ...");
118.        Console.ReadLine();
119.         
120.        if (sListener.Connected)
121.        {
122.            sListener.Shutdown(SocketShutdown.Receive);
123.            sListener.Close();
124.        }
125.    }
126. 
127. 
128.    /// <summary>
129.    /// Asynchronously accepts an incoming connection attempt and creates
130.    /// a new Socket to handle remote host communication.
131.    /// </summary>    
132.    /// <param name="ar">the status of an asynchronous operation
133.    /// 
134.    public static void AcceptCallback(IAsyncResult ar)
135.    {
136.        Socket listener = null;
137. 
138.        // A new Socket to handle remote host communication
139.        Socket handler = null;
140.        try
141.        {
142.            // Receiving byte array
143.            byte[] buffer = new byte[1024];
144.            // Get Listening Socket object
145.            listener = (Socket)ar.AsyncState;
146.            // Create a new socket
147.            handler = listener.EndAccept(ar);
148. 
149.            // Using the Nagle algorithm
150.            handler.NoDelay = true;
151. 
152.            // Creates one object array for passing data
153.            object[] obj = new object[2];
154.            obj[0] = buffer;
155.            obj[1] = handler;
156. 
157.            // Begins to asynchronously receive data
158.            handler.BeginReceive(
159.                buffer,        // An array of type Byt for received data
160.                0,             // The zero-based position in the buffer
161.                buffer.Length, // The number of bytes to receive
162.                SocketFlags.None,// Specifies send and receive behaviors
163.                new AsyncCallback(ReceiveCallback),//An AsyncCallback delegate
164.                obj            // Specifies infomation for receive operation
165.                );
166. 
167.            // Begins an asynchronous operation to accept an attempt
168.            AsyncCallback aCallback = new AsyncCallback(AcceptCallback);
169.            listener.BeginAccept(aCallback, listener);
170.        }
171.        catch (Exception ex)
172.        {
173.            Console.WriteLine("Exception: {0}", ex.ToString());
174.        }
175.    }
176. 
177.    /// <summary>
178.    /// Asynchronously receive data from a connected Socket.
179.    /// </summary>
180.    /// <param name="ar">
181.    /// the status of an asynchronous operation
182.    /// 
183.    public static void ReceiveCallback(IAsyncResult ar)
184.    {
185.        try
186.        {
187.            // Fetch a user-defined object that contains information
188.            object[] obj = new object[2];
189.            obj = (object[])ar.AsyncState;
190. 
191.            // Received byte array
192.            byte[] buffer = (byte[])obj[0];
193. 
194.            // A Socket to handle remote host communication.
195.            Socket handler = (Socket)obj[1];
196. 
197.            // Received message
198.            string content = string.Empty;
199. 
200.            // The number of bytes received.
201.            int bytesRead = handler.EndReceive(ar);
202. 
203.            if (bytesRead > 0)
204.            {
205.                content += Encoding.Unicode.GetString(buffer, 0,
206.                    bytesRead);
207.                // If message contains "<client quit="">", finish receiving
208.                if (content.IndexOf("<client quit="">") > -1)
209.                {
210.                    // Convert byte array to string
211.                    string str =
212.                        content.TrimEnd(("<client quit="">").ToCharArray());
213.                    Console.WriteLine(
214.                        "Read {0} bytes from client.\n Data: {1}",
215.                        str.Length, str);
216. 
217.                    // Prepare the reply message
218.                    byte[] byteData =
219.                        Encoding.Unicode.GetBytes(str);
220. 
221.                    // Sends data asynchronously to a connected Socket
222.                    handler.BeginSend(byteData, 0, byteData.Length, 0,
223.                        new AsyncCallback(SendCallback), handler);
224.                }
225.                else
226.                {
227.                    // Continues to asynchronously receive data
228.                    byte[] buffernew = new byte[1024];
229.                    obj[0] = buffernew;
230.                    obj[1] = handler;
231.                    handler.BeginReceive(buffernew, 0, buffernew.Length,
232.                        SocketFlags.None,
233.                        new AsyncCallback(ReceiveCallback), obj);
234.                }
235.            }
236.        }
237.        catch (Exception ex)
238.        {
239.            Console.WriteLine("Exception: {0}", ex.ToString());
240.        }
241.    }
242. 
243.    /// <summary>
244.    /// Sends data asynchronously to a connected Socket.
245.    /// </summary>
246.    /// <param name="ar">
247.    /// The status of an asynchronous operation
248.    /// 
249.    public static void SendCallback(IAsyncResult ar)
250.    {
251.        try
252.        {
253.            // A Socket which has sent the data to remote host
254.            Socket handler = (Socket)ar.AsyncState;
255. 
256.            // The number of bytes sent to the Socket
257.            int bytesSend = handler.EndSend(ar);
258.            Console.WriteLine(
259.                "Sent {0} bytes to Client",bytesSend);
260.        }
261.        catch (Exception ex)
262.        {
263.            Console.WriteLine("Exception: {0}", ex.ToString());
264.        }
265.    }
266.}
267.</client></client></client>
Posted by Y2K
,

0008. CSWindowsHook

Sample Codes 2010. 1. 5. 16:26
Windows Hooking의 경우에는 Windows message queue에 대한 이해가 좀 필요하다.
Windows는 Windows Message Queue를 통해서 각각의 Message를 전달하고, 그 Message에 따라 각기 다른 Action을 행한다.
WM_PAINT의 경우에는 화면을 그리라는 Message가 되고, WM_MOUSE의 경우에는 Mouse의 움직임에 따라 발생되는 Windows
Message이다.

Hooking은 이런 WIndows Message Queue에 Hook을 걸어서, 원래 처리되어야지 되는 함수가 아닌, 사용자 지정 Method에서
처리하게 하는 방법이다. 이것을 이용하면 Ctrl+Alt+Del의 기능도 막아버릴 수 있으며, 마우스를 움직여서 다른 동작을 하는 것도
막는 것이 가능하다. 또한 Mouse나 Keyboard의 모든 기록들을 저장할 수 있기 때문에 Windows에서 Cracking을 하는 경우에
왕왕 사용되는 방법이다.

먼저, WIN32 함수인 SetWindowsHookEx 함수를 DllImport시켜서 가지고 온다. 필요한 Native method의 선언은 다음과 같다.

001.internal delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);
002. 
003.internal class NativeMethods
004.{
005.    /// <summary>
006.    /// Hooking WIN32 API
007.    /// dwThreadId가 0인 경우에는 전역 hook
008.    /// 특정 handler안에서 Hooking을 하는 경우에는 Handle 값을 넣어준다.
009.    /// </summary>
010.    /// <param name="hookType">
011.    /// <param name="callback">Hooking을 한 이후에 받을 method의 주소값 delegate된 method를 넣어줄수 있다.
012.    /// <param name="hMod">
013.    /// <param name="dwThreadId">
014.    /// <returns></returns>
015.    [DllImport("user32.dll", CharSet = CharSet.Auto)]
016.    public static extern IntPtr SetWindowsHookEx(HookType hookType, HookProc callback, IntPtr hMod, uint dwThreadId);
017. 
018.    [DllImport("user32.dll", CharSet = CharSet.Auto)]
019.    public static extern bool UnhookWindowsHookEx(IntPtr hhk);
020. 
021.    [DllImport("user32.dll", CharSet = CharSet.Auto)]
022.    public static extern int CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
023.}
024. 
025.internal static class HookCodes
026.{
027.    public const int HC_ACTION = 0;
028.    public const int HC_GETNEXT = 1;
029.    public const int HC_SKIP = 2;
030.    public const int HC_NOREMOVE = 3;
031.    public const int HC_NOREM = HC_NOREMOVE;
032.    public const int HC_SYSMODALON = 4;
033.    public const int HC_SYSMODALOFF = 5;
034.}
035. 
036.internal enum HookType
037.{
038.    WH_KEYBOARD = 2,
039.    WH_MOUSE = 7,
040.    WH_KEYBOARD_LL = 13,
041.    WH_MOUSE_LL = 14
042.}
043. 
044.[StructLayout(LayoutKind.Sequential)]
045.internal class POINT
046.{
047.    public int x;
048.    public int y;
049.}
050. 
051./// <summary>
052./// The MSLLHOOKSTRUCT structure contains information about a low-level keyboard
053./// input event.
054./// </summary>
055.[StructLayout(LayoutKind.Sequential)]
056.internal struct MOUSEHOOKSTRUCT
057.{
058.    public POINT pt;        // The x and y coordinates in screen coordinates
059.    public int hwnd;        // Handle to the window that'll receive the mouse message
060.    public int wHitTestCode;
061.    public int dwExtraInfo;
062.}
063. 
064./// <summary>
065./// The MOUSEHOOKSTRUCT structure contains information about a mouse event passed
066./// to a WH_MOUSE hook procedure, MouseProc.
067./// </summary>
068.[StructLayout(LayoutKind.Sequential)]
069.internal struct MSLLHOOKSTRUCT
070.{
071.    public POINT pt;        // The x and y coordinates in screen coordinates.
072.    public int mouseData;   // The mouse wheel and button info.
073.    public int flags;
074.    public int time;        // Specifies the time stamp for this message.
075.    public IntPtr dwExtraInfo;
076.}
077. 
078.internal enum MouseMessage
079.{
080.    WM_MOUSEMOVE = 0x0200,
081.    WM_LBUTTONDOWN = 0x0201,
082.    WM_LBUTTONUP = 0x0202,
083.    WM_LBUTTONDBLCLK = 0x0203,
084.    WM_RBUTTONDOWN = 0x0204,
085.    WM_RBUTTONUP = 0x0205,
086.    WM_RBUTTONDBLCLK = 0x0206,
087.    WM_MBUTTONDOWN = 0x0207,
088.    WM_MBUTTONUP = 0x0208,
089.    WM_MBUTTONDBLCLK = 0x0209,
090. 
091.    WM_MOUSEWHEEL = 0x020A,
092.    WM_MOUSEHWHEEL = 0x020E,
093. 
094.    WM_NCMOUSEMOVE = 0x00A0,
095.    WM_NCLBUTTONDOWN = 0x00A1,
096.    WM_NCLBUTTONUP = 0x00A2,
097.    WM_NCLBUTTONDBLCLK = 0x00A3,
098.    WM_NCRBUTTONDOWN = 0x00A4,
099.    WM_NCRBUTTONUP = 0x00A5,
100.    WM_NCRBUTTONDBLCLK = 0x00A6,
101.    WM_NCMBUTTONDOWN = 0x00A7,
102.    WM_NCMBUTTONUP = 0x00A8,
103.    WM_NCMBUTTONDBLCLK = 0x00A9
104.}
105. 
106./// <summary>
107./// The structure contains information about a low-level keyboard input event.
108./// </summary>
109.[StructLayout(LayoutKind.Sequential)]
110.internal struct KBDLLHOOKSTRUCT
111.{
112.    public int vkCode;      // Specifies a virtual-key code
113.    public int scanCode;    // Specifies a hardware scan code for the key
114.    public int flags;
115.    public int time;        // Specifies the time stamp for this message
116.    public int dwExtraInfo;
117.}
118. 
119.internal enum KeyboardMessage
120.{
121.    WM_KEYDOWN = 0x0100,
122.    WM_KEYUP = 0x0101,
123.    WM_SYSKEYDOWN = 0x0104,
124.    WM_SYSKEYUP = 0x0105
125.}

여기에서 구성된 Hooking method들은 다음과 같다.

01.private bool SetGlobalLLMouseHook()
02.{
03.    // Create an instance of HookProc.
04.    globalLLMouseHookCallback = new HookProc(this.LowLevelMouseProc);
05. 
06.    hGlobalLLMouseHook = NativeMethods.SetWindowsHookEx(
07.        HookType.WH_MOUSE_LL,  // Must be LL for the global hook
08.        globalLLMouseHookCallback,
09.        // Get the handle of the current module
10.        Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]),
11.        // The hook procedure is associated with all existing threads running
12.        // in the same desktop as the calling thread.
13.        0);
14.    return hGlobalLLMouseHook != IntPtr.Zero;
15.}
16. 
17.public int LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam)
18.{
19.    if(nCode >= 0)
20.    {
21.        // Marshal the MSLLHOOKSTRUCT data from the callback lParam
22.        MSLLHOOKSTRUCT mouseLLHookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
23. 
24.        // Get the mouse WM from the wParam parameter
25.        MouseMessage wmMouse = (MouseMessage)wParam;
26. 
27.        // Display the current mouse coordinates and the message
28.        String log = String.Format("X = {0} Y = {1}  ({2})\r\n", mouseLLHookStruct.pt.x, mouseLLHookStruct.pt.y, wmMouse);
29.        tbLog.AppendText(log);
30.    }
31. 
32.    // Pass the hook information to the next hook procedure in chain
33.    return NativeMethods.CallNextHookEx(hGlobalLLMouseHook, nCode, wParam, lParam);
34.}
Posted by Y2K
,
별다를 것이 없는 코드.
Visual Studio에서 Generate되는 code만을 간단히 이용하지만, Windows EventLog를 사용하는 법이 나온 부분만 체크해보면 될 것 같다.
또 하나가 있다면, ProjectInstaller 역시 살펴 볼 내용.

Windows Service를 등록하기 위해서는 InstallUtil을 이용해서 Service를 등록시켜야지 되는데 이때 등록할 ServiceName과 Service의
이름을 일치시켜주는 것이 필요하다.


01.private void InitializeComponent()
02.{
03.    ///서비스 등록 Account와 Password, UserName을 명시해준다.
04.    this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
05.    this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
06.    //
07.    // serviceProcessInstaller1
08.    //
09.    this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalService;
10.    this.serviceProcessInstaller1.Password = null;
11.    this.serviceProcessInstaller1.Username = null;
12.    //
13.    // serviceInstaller1
14.    //
15.    ///서비스에 대한 내용을 기술한다. ServiceName의 경우에는 작성한 ServiceName과 반드시 일치해야지 된다.
16.    this.serviceInstaller1.Description = "All-In-One Code Framework Windows Service example";
17.    this.serviceInstaller1.DisplayName = "CSWindowsService Sample Service";
18.    this.serviceInstaller1.ServiceName = "CSWindowsService";
19.    //
20.    // ProjectInstaller
21.    //
22.    this.Installers.AddRange(new System.Configuration.Install.Installer[] {
23.                                this.serviceProcessInstaller1,
24.                                this.serviceInstaller1});
25.}

01./// Required method for Designer support - do not modify
02./// the contents of this method with the code editor.
03./// Windows EventLog에 대한 초기화를 행한다.
04.private System.Diagnostics.EventLog eventLog1;
05.private void InitializeComponent()
06.{
07.    this.eventLog1 = new System.Diagnostics.EventLog();
08.    ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).BeginInit();
09.    //
10.    // eventLog1
11.    //
12.    this.eventLog1.Log = "Application";
13.    this.eventLog1.Source = "CSWindowsService";
14.    //
15.    // MyService
16.    //
17.    this.ServiceName = "CSWindowsService";
18.    ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).EndInit();
19.}
Posted by Y2K
,
WPF를 이용한 Image animation

System.Windows.Media.Animation.StoryBoard controller를 이용해서 Image Animation을 할 수 있다.
Image Animation 형태는 StoryBoard Controller의 Property들을 변경시키면 가능하다.



01.int nextImageIndex;
02.List<bitmapimage> images = new List<bitmapimage>();
03. 
04.private void Window_Loaded(object sender, RoutedEventArgs e)
05.{
06.    // initialize the images collection
07.    images.Add(new BitmapImage(new Uri("Images/image1.jpg", UriKind.Relative)));
08.    images.Add(new BitmapImage(new Uri("Images/image2.jpg", UriKind.Relative)));
09.    images.Add(new BitmapImage(new Uri("Images/image3.jpg", UriKind.Relative)));
10.    images.Add(new BitmapImage(new Uri("Images/image4.jpg", UriKind.Relative)));
11. 
12.    nextImageIndex = 2;
13.}
14.        
15.private void VisbleToInvisible_Completed(object sender, EventArgs e)
16.{
17.    // change the source of the myImage1 to the next image to be shown
18.    // and increase the nextImageIndex
19.    this.myImage1.Source = images[nextImageIndex++];
20. 
21.    // if the nextImageIndex exceeds the top bound of the ocllection,
22.    // get it to 0 so as to show the first image next time
23.    if (nextImageIndex == images.Count)
24.    {
25.        nextImageIndex = 0;
26.    }
27. 
28.    // get the InvisibleToVisible storyboard and start it
29.    Storyboard sb = FindResource("InvisibleToVisible") as Storyboard;
30.    if(sb != null)
31.        sb.Begin(this);
32. 
33.}
34. 
35.private void InvisibleToVisible_Completed(object sender, EventArgs e)
36.{
37.    // change the source of the myImage2 to the next image to be shown
38.    // and increase the nextImageIndex
39.    this.myImage2.Source = images[nextImageIndex++];
40. 
41.    // if the nextImageIndex exceeds the top bound of the ocllection,
42.    // get it to 0 so as to show the first image next time
43.    if (nextImageIndex == images.Count)
44.    {
45.        nextImageIndex = 0;
46.    }
47. 
48.    // get the VisibleToInvisible storyboard and start it
49.    Storyboard sb = this.FindResource("VisibleToInvisible") as Storyboard;
50.    if(sb != null)
51.        sb.Begin(this);
52.}  
53.</bitmapimage></bitmapimage>
Posted by Y2K
,
RSAServiceProvider를 이용해서 xml 파일에 서명 및 Decryption 하는 과정
RSAServiceProvider를 제공된 public key를 이용해서 얻어내는 것이 이 코드의 핵심.



001.private String publicOnlyKey;
002.private void btnSign_Click(object sender, EventArgs e)
003.{
004.    try
005.    {
006.        /////////////////////////////////////////////////////////////////
007.        // Create a new RSA signing key and export public key for
008.        // verification.
009.         
010.        RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider();
011.         
012.        //Public Key exported
013.        //Public Key 뿐 아니라 Private Key도 얻어내는 것이 가능하다. 사용자에게 Key를 보내거나 저장할 때 이용 가능
014.        publicOnlyKey = rsaKey.ToXmlString(false);
015.        tbxRSAParameters.Text = publicOnlyKey;
016.         
017.        /////////////////////////////////////////////////////////////////
018.        // Sign the XML document.
019.        //
020. 
021.        SignXml(xmlDoc, rsaKey);
022.        MessageBox.Show("XML file signed.");
023. 
024. 
025.        /////////////////////////////////////////////////////////////////
026.        // Save and display the signed document.
027.        //
028. 
029.        xmlDoc.Save("test1.xml");
030.        tbxDigitalSignature.Text = xmlDoc.OuterXml;
031.    }
032.    catch (Exception ex)
033.    {
034.        Console.WriteLine(ex.Message);
035.    }
036.}
037. 
038.///XML파일을 RSA를 이용해서 서명. SignedXml class가 있는 것을 기억하고 있을것!
039.public static void SignXml(XmlDocument Doc, RSA Key)
040.{
041.    // Check arguments.
042.    if (Doc == null)
043.        throw new ArgumentException("Doc");
044.    if (Key == null)
045.        throw new ArgumentException("Key");
046. 
047.    try
048.    {
049.        // Create a SignedXml object to generate signature.
050.        SignedXml signedXml = new SignedXml(Doc);
051. 
052.        // Add the key to the SignedXml document
053.        signedXml.SigningKey = Key;
054. 
055.        // Create a reference to be signed
056.        Reference reference = new Reference();
057.        reference.Uri = "";
058. 
059.        // Add an enveloped transformation to the reference
060.        XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
061.        reference.AddTransform(env);
062. 
063.        // Add the reference to the SignedXml object
064.        signedXml.AddReference(reference);
065. 
066.        // Compute the signature
067.        signedXml.ComputeSignature();
068. 
069.        // Get the XML representation of the signature and save
070.        // it to an XmlElement object.
071.        XmlElement xmlDigitalSignature = signedXml.GetXml();
072. 
073.        // Append the element to the XML document.
074.        Doc.DocumentElement.AppendChild(Doc.ImportNode(xmlDigitalSignature, true));
075.    }
076.    catch (Exception ex)
077.    {
078.        MessageBox.Show(ex.Message);
079.    }
080.}
081. 
082.private void btnVerify_Click(object sender, EventArgs e)
083.{
084.    /////////////////////////////////////////////////////////////////////
085.    // Create a new RSA signing key and import public key for
086.    // verification.
087.    //
088. 
089.    //NOTE:Public RSA Key를 이용해서 RSACryptoService Generate
090.    RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider();
091.    rsaKey.FromXmlString(publicOnlyKey);
092.    /////////////////////////////////////////////////////////////////////
093.    // Load the signed XML, and call VerifyXml to verify the signature of
094.    // the signed XML.
095.    //
096. 
097.    XmlDocument xmlDoc = new XmlDocument();
098.    xmlDoc.Load("test1.xml");
099. 
100.    bool result = VerifyXml(xmlDoc, rsaKey);
101. 
102.    if (result)
103.    {
104.        MessageBox.Show("The XML signature is valid.");
105.    }
106.    else
107.    {
108.        MessageBox.Show("The XML signature is not valid.");
109.    }
110.}
111. 
112.public static Boolean VerifyXml(XmlDocument Doc, RSA Key)
113.{
114.    // Check arguments.
115.    if (Doc == null)
116.        throw new ArgumentException("Doc");
117.    if (Key == null)
118.        throw new ArgumentException("Key");
119. 
120. 
121.    /////////////////////////////////////////////////////////////////////
122.    // Create a SignedXml object to verify the signature
123.    //
124. 
125.    SignedXml signedXml = new SignedXml(Doc);
126. 
127.    // Find Signature node and create a new XmlNodeList object
128.    XmlNodeList nodeList = Doc.GetElementsByTagName("Signature");
129. 
130.    // Throw an exception if no signature was found.
131.    if (nodeList.Count <= 0)
132.    {
133.        throw new CryptographicException(
134.            "Verification failed:" +
135.            " No Signature was found in the document.");
136.    }
137. 
138.    // This example only supports one signature for entire XML document
139.    if (nodeList.Count >= 2)
140.    {
141.        throw new CryptographicException(
142.            "Verification failed: More that one signature was found.");
143.    }
144. 
145.    // Load the first <signature> node. 
146.    signedXml.LoadXml((XmlElement)nodeList[0]);
147. 
148.    // Check the signature and return the result.
149.    return signedXml.CheckSignature(Key);
150.}
151. 
152.private void btnChangeXML_Click(object sender, EventArgs e)
153.{
154.    // Modify the value of the Xml document for test.
155. 
156.    XDocument xDoc = XDocument.Load("test1.xml");
157. 
158.    if (xDoc != null)
159.    {
160.        xDoc.Element("invoice").Element("items").
161.            Element("creditcard").Element("number").SetValue("19834210");
162. 
163.        xDoc.Save("test1.xml");
164. 
165.        tbxModifiedMessage.Text = xDoc.ToString();
166.    }
167.}
168.</signature>
Posted by Y2K
,

0004. XmlGeneral

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


001./****************************** Module Header ******************************\
002.* Module Name:  Program.cs
003.* Project:      CSXmlGeneral
004.* Copyright (c) Microsoft Corporation.
005.*
006.* This C# sample project shows how to read a XML file by using XmlTextReader
007.* or XmlNodeReader. It also shows, instead of using forward-only reader, how
008.* to read, modify, and update Xml element using the XmlDocument class. This
009.* class will load the whole document into memory for modification and we can
010.* save the modified XML file to the file system.
011.*
012.* The XML file used by the demo has this format:
013.*
014.* <catalog>
015.*  <book id="bk101">
016.*    <author>Gambardella, Matthew</author>
017.*    <title>XML Developer's Guide</title>
018.*    <genre>Computer</genre>
019.*    <price>44.95</price>
020.*    <publish_date>2000-10-01</publish_date>
021.*    <description>
022.*      An in-depth look at creating applications
023.*      with XML.
024.*    </description>
025.*  </book>
026.*  <book>
027.*   ...
028.*  </book>
029.* <catalog>
030.*
031.* This source is subject to the Microsoft Public License.
033.* All other rights reserved.
034.*
035.* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
036.* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
037.* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
038.\***************************************************************************/
039. 
040.#region Using directives
041.using System;
042.using System.Collections.Generic;
043.using System.Linq;
044.using System.Text;
045.using System.Xml;
046.#endregion
047. 
048. 
049.class Program
050.{
051.    static void Main(string[] args)
052.    {
053.        /////////////////////////////////////////////////////////////////////
054.        // Read XML document using the XmlTextReader class.
055.        //
056. 
057.        // The XmlTextReader acts as a reader pointer that only moves forward.
058.        // Because it always moves forward and read a piece of data into
059.        // memory buffer, it has better performance than the XmlDocument
060.        // class which loads the whole document into memory.
061. 
062.        Console.WriteLine("Loading XML using XmlTextReader...");
063. 
064.        XmlTextReader xmlTextReader = new XmlTextReader(@"Books.xml");
065.        xmlTextReader.WhitespaceHandling = WhitespaceHandling.None;
066. 
067.        while (xmlTextReader.Read())
068.        {
069.            if (xmlTextReader.Name == "book")
070.            {
071.                Console.WriteLine(xmlTextReader.GetAttribute("id") + ": ");
072. 
073.                xmlTextReader.Read();
074.                string author = xmlTextReader.ReadElementContentAsString();
075.                string title = xmlTextReader.ReadElementContentAsString();
076.                string genre = xmlTextReader.ReadElementContentAsString();
077.                string price = xmlTextReader.ReadElementContentAsString();
078.                string publishDate = xmlTextReader.ReadElementContentAsString();
079.                string description = xmlTextReader.ReadElementContentAsString();
080. 
081.                Console.WriteLine(genre + " book \"" + title + "\" written by \"" +
082.                    author + "\", published on " + publishDate);
083.                Console.WriteLine(description);
084.            }
085.        }
086. 
087.        xmlTextReader.Close();
088. 
089. 
090.        /////////////////////////////////////////////////////////////////////
091.        // Read XML document using the XmlDocument and XmlNodeReader classes.
092.        //
093. 
094.        // XmlNodeReader is similar to XmlTextReader but accepts an XmlNode
095.        // instance as target to read. The following code shows how to use
096.        // XmlDocument and XmlNodeReader to retrieve XML information. It is
097.        // also a forward-only reader.
098. 
099.        Console.WriteLine("Loading XML using XmlDocument & XmlNodeReader...");
100. 
101.        XmlDocument xmlDocument = new XmlDocument();
102.        xmlDocument.Load(@"Books.xml");
103.        XmlNodeList xmlNodes = xmlDocument.GetElementsByTagName("book");
104.        foreach (XmlNode node in xmlNodes)
105.        {
106.            Console.WriteLine(node.Attributes["id"].Value + ":");
107. 
108.            XmlNodeReader xmlNodeReader = new XmlNodeReader(node);
109.            xmlNodeReader.Read();
110.            xmlNodeReader.Read();
111.            string author = xmlNodeReader.ReadElementContentAsString();
112.            string title = xmlNodeReader.ReadElementContentAsString();
113.            string genre = xmlNodeReader.ReadElementContentAsString();
114.            string price = xmlNodeReader.ReadElementContentAsString();
115.            string publishDate = xmlNodeReader.ReadElementContentAsString();
116.            string description = xmlNodeReader.ReadElementContentAsString();
117. 
118.            Console.WriteLine(genre + " book \"" + title + "\" written by \"" +
119.                author + "\", published on " + publishDate);
120.            Console.WriteLine(description);
121.        }
122. 
123. 
124.        /////////////////////////////////////////////////////////////////////
125.        // Make changes to the XmlDocument.
126.        //
127. 
128.        // Modify a node value by first calling SelectSingleNode to navigate
129.        // to that node and by setting its InnerText property to change its
130.        // content.
131.        XmlNode nodeToModify = xmlDocument.DocumentElement.SelectSingleNode(
132.            "book/genre");
133.        nodeToModify.InnerText = "XML Tech";
134. 
135.        // Add a new XML node. In XML programming, we always call
136.        // XMLDocument.Create*** to create an attribute or element. After
137.        // that, we can add it into where we want by calling Node.AppendChild
138.        XmlElement newElement = xmlDocument.CreateElement("book");
139.        XmlAttribute newAttribute = xmlDocument.CreateAttribute("id");
140.        newAttribute.Value = "bk103";
141.        XmlElement authorElement = xmlDocument.CreateElement("author");
142.        authorElement.InnerText = "Mark Russinovich,David Solomon,Alex Ionecsu";
143.        XmlElement titleElement = xmlDocument.CreateElement("title");
144.        titleElement.InnerText = "Windows Internals, 5th edition";
145.        XmlElement genreElement = xmlDocument.CreateElement("genre");
146.        genreElement.InnerText = "Windows Server 2008";
147.        XmlElement priceElement = xmlDocument.CreateElement("price");
148.        priceElement.InnerText = "69.99";
149.        XmlElement publishDateElement = xmlDocument.CreateElement("publish_date");
150.        publishDateElement.InnerText = "2009-6-17";
151.        XmlElement descriptionElement = xmlDocument.CreateElement("description");
152.        descriptionElement.InnerText = "Windows Internals, 5th edition is the" +
153.            " update to Windows Internals, 4th edition to cover Windows Vista" +
154.            " and Windows Server 2008 (32-bit and 64-bit).";
155. 
156.        newElement.Attributes.Append(newAttribute);
157.        newElement.AppendChild(authorElement);
158.        newElement.AppendChild(titleElement);
159.        newElement.AppendChild(genreElement);
160.        newElement.AppendChild(priceElement);
161.        newElement.AppendChild(publishDateElement);
162.        newElement.AppendChild(descriptionElement);
163.        xmlDocument.DocumentElement.AppendChild(newElement);
164. 
165.        // Save the changes
166.        xmlDocument.Save("Modified Books.xml");
167. 
168.        // XmlLDocument does not have Close or Dispose method because it is
169.        // an in-memory representation of an XML document. Once read, the
170.        // file is no-longer needed.
171.    }
172.}
173.</catalog></catalog>

01.<!--?xml version="1.0" encoding="utf-8" ?-->
02.<catalog>
03.  <book id="bk101">
04.    <author>Gambardella, Matthew</author>
05.    <title>XML Developer's Guide</title>
06.    <genre>Computer</genre>
07.    <price>44.95</price>
08.    <publish_date>2000-10-01</publish_date>
09.    <description>
10.      An in-depth look at creating applications
11.      with XML.
12.    </description>
13.  </book>
14.  <book id="bk102">
15.    <author>Ralls, Kim</author>
16.    <title>Midnight Rain</title>
17.    <genre>Fantasy</genre>
18.    <price>5.95</price>
19.    <publish_date>2000-12-16</publish_date>
20.    <description>
21.      A former architect battles corporate zombies,
22.      an evil sorceress, and her own childhood to become queen
23.      of the world.
24.    </description>
25.  </book>
26.</catalog>
Posted by Y2K
,
.NET에서 Serialization은 객체를 저장하고, 객체를 다시 불러오는데 매우 유용하다. 그리고 네트워크로 Serialization된 객체를 전송하고,
다시 그 객체를 사용할 수 도 있는 .NET에서 핵심적인 기능중 하나이다.

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


001./****************************** Module Header ******************************\
002.* Module Name:  Program.cs
003.* Project:      CSXmlSerialization
004.* Copyright (c) Microsoft Corporation.
005.*
006.* This sample shows how to serialize an in-memory object to a local xml file
007.* and how to deserialize the xml file back to an in-memory object using
008.* C#. The designed MySerializableType includes int, string, generic, as well
009.* as customized type field and property.
010.*
011.* This source is subject to the Microsoft Public License.
013.* All other rights reserved.
014.*
015.* History:
016.* * 7/29/2009 3:00 PM Colbert Zhou Created
017.* * 8/20/2009 12:01 AM Jialiang Ge Reviewed
018.\***************************************************************************/
019. 
020.#region Using directives
021.using System;
022.using System.Collections.Generic;
023.using System.Linq;
024.using System.Text;
025.using System.Xml;
026.using System.Xml.Serialization;
027.using System.IO;
028.using System.Collections;
029.#endregion
030. 
031. 
032.namespace CSXmlSerialization
033.{
034.    class Program
035.    {
036.        static void Main(string[] args)
037.        {
038.            /////////////////////////////////////////////////////////////////
039.            // Serialize the object to an XML file.
040.            //
041. 
042.            // Create and initialize a MySerializableType instance.
043.            MySerializableType instance = new MySerializableType();
044.            instance.BoolValue = true;
045.            instance.IntValue = 1;
046.            instance.StringValue = "Test String";
047.            instance.ListValue.Add("List Item 1");
048.            instance.ListValue.Add("List Item 2");
049.            instance.ListValue.Add("List Item 3");
050.            instance.AnotherTypeValue = new AnotherType();
051.            instance.AnotherTypeValue.IntValue = 2;
052.            instance.AnotherTypeValue.StringValue = "Inner Test String";
053. 
054.            // Create the serializer
055.            XmlSerializer serializer = new XmlSerializer(typeof(MySerializableType));
056. 
057.            // Serialize the object to an XML file
058.            using (StreamWriter streamWriter = File.CreateText(
059.                "CSXmlSerialization.xml"))
060.            {
061.                serializer.Serialize(streamWriter, instance);
062.            }
063. 
064. 
065.            /////////////////////////////////////////////////////////////////
066.            // Deserialize from a XML file to an object instance.
067.            //
068. 
069.            // Deserialize the object
070.            MySerializableType deserializedInstance;
071.            using (StreamReader streamReader = File.OpenText(
072.                "CSXmlSerialization.xml"))
073.            {
074.                deserializedInstance = serializer.Deserialize(streamReader)
075.                    as MySerializableType;
076.            }
077. 
078.            // Dump the object
079.            Console.WriteLine("BoolValue: {0}", deserializedInstance.BoolValue);
080.            Console.WriteLine("IntValue: {0}", deserializedInstance.IntValue);
081.            Console.WriteLine("StringValue: {0}", deserializedInstance.StringValue);
082.            Console.WriteLine("AnotherTypeValue.IntValue: {0}",
083.                deserializedInstance.AnotherTypeValue.IntValue);
084.            Console.WriteLine("AnotherTypeValue.StringValue: {0}",
085.                deserializedInstance.AnotherTypeValue.StringValue);
086.            Console.WriteLine("ListValue: ");
087.            foreach (object obj in deserializedInstance.ListValue)
088.            {
089.                Console.WriteLine(obj.ToString());
090.            }
091.        }
092.    }
093. 
094. 
095.    /// <summary>
096.    /// Serializable Type Declaration
097.    /// </summary>
098.    [Serializable()]
099.    public class MySerializableType
100.    {
101.        // String field and property
102.        private string stringValue;
103.        public string StringValue
104.        {
105.            get { return stringValue; }
106.            set { stringValue = value; }
107.        }
108. 
109.        // Bool field and property
110.        private bool boolValue;
111.        public bool BoolValue
112.        {
113.            get { return boolValue; }
114.            set { boolValue = value; }
115.        }
116. 
117.        // Int field and property
118.        private int intValue;
119.        public int IntValue
120.        {
121.            get { return intValue; }
122.            set { intValue = value; }
123.        }
124. 
125.        // Another type field and property
126.        private AnotherType anotherTypeValue;
127.        public AnotherType AnotherTypeValue
128.        {
129.            get { return anotherTypeValue; }
130.            set { anotherTypeValue = value; }
131.        }
132. 
133.        // Generic type field and property
134.        private List<string> listValue = new List<string>();
135.        public List<string> ListValue
136.        {
137.            get { return listValue; }
138.            set { listValue = value; }
139.        }
140. 
141.        // Ignore a field using NonSerialized attribute
142.        [NonSerialized()]
143.        private int ignoredField = 1;
144.    }
145. 
146.    /// <summary>
147.    /// Another Type Declaration
148.    /// </summary>
149.    [Serializable()]
150.    public class AnotherType
151.    {
152.        private string stringValue;
153.        public string StringValue
154.        {
155.            get { return stringValue; }
156.            set { stringValue = value; }
157.        }
158. 
159.        private int intValue;
160.        public int IntValue
161.        {
162.            get { return intValue; }
163.            set { intValue = value; }
164.        }
165.    }
166.}
167.</string></string></string>
Posted by Y2K
,