using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlServerCe; // SQL Server Compact 3.5 사용시 추가하시오

namespace Genealogy
{
    public class DB_Management
    {
        #region DB 전역변수 선언
        private string connentionString = @"Data Source=C:\Documents and Settings\Administrator\My Documents\DB.SDF;" +
                "Password=1234;";

        private SqlCeConnection con = null;
        private SqlCeCommand cmd = null;
        private SqlCeTransaction trn = null;

        public Boolean ExecuteQueryFlag;
        #endregion
       
        #region 생성자(초기화
        public DB_Management()
        {
            // 데이터베이스 연결
            SqlCeConnection con = new SqlCeConnection(connentionString);
            // 데이터베이스 커맨드 생성
            SqlCeCommand cmd = new SqlCeCommand();
            // 트랜잭션 생성
            SqlCeTransaction trn = con.BeginTransaction();
            ExecuteQueryFlag = false;
        }
        #endregion

        #region DB 연결
        public void DB_Connection()
        {
            con.Open();
        }
        #endregion

        #region Command Connection
        private void CommConnection(string Commandtext)
        {
            // 커맨드에 커넥션을 연결
            cmd.Connection = con;

            cmd.Transaction = trn;

            // 쿼리 생성 : Insert 쿼리
            cmd.CommandText = Commandtext;

            // 쿼리 실행
            cmd.ExecuteNonQuery();
        }
        #endregion
      
        #region Insert
        public void DB_Record_Insert(string TableID, string RecordName)
        {
            string InsertRecordName = "INSERT INTO" + TableID + "VALUES('" +
                                      RecordName + "')";
           
            CommConnection(InsertRecordName);

            if(ExecuteQueryFlag == true)
            {
                // 커밋
                trn.Commit();
            }
            else
            {
                // 롤백
                trn.Rollback();
            }

            con.Close();
           
        }
        #endregion

        #region Select
        public void DB_Record_Select(int Indexnumber, params string[] args)
        {
            string SelectRecordName = string.Empty;
            
            if (Indexnumber < 0)
            {
                // select 쿼리로 변경
                SelectRecordName = "SELECT * FROM" + args[0];
            }
            con.Close();
        }
        #endregion
    }
}

비번은 마음에 드는걸로 바꾸면 될듯 하다.
commit과 rollback이 되기때문에 compact db를 자주 사용하는 편이다. 꽤 쓸만하다.

string[] names = {"Burke", "Connor", "Frank",
                                 "Everett","Albert","George",
                                 "Harris","David"};
            /* 여기에서 로컬 변수 query 가 "쿼리식"에서 초기화 됩니다.
             * 쿼리 식은 표준 쿼리 연산자 또는 도메인 고유의 연산자의 몇 개의
             * 쿼리 연산자를 1개 이상적용하고, 1개 이상의 정보 소스에 대해
             * 연산을 실시 합니다. 이 식에서는 세가지 표준 쿼리 연산자, where,
             * orderBy 및 select를 사용합니다.
             * visual basic 9.0에서도 LINQ가 지원 됩니다. 상기 구문을 Visual Basic 9.0
             * 으로 기술하면 다음과 같습니다. */

            /* LINQ는 VS2008 과 .NET 3.5에 포함된 새로운 기능중 하나 입니다.
             * LINQ는 Data 쿼리의 개념을 닷넷에서의 프로그래밍 컨셉으로 만들었고 ,
             * 원하는 언어로 질의를 행하는것을 가능하게 하였습니다. */

            IEnumerable<string> query = from s in names
                                        where s != "Burke"
                                        orderby s
                                        select s.ToUpper();

            foreach (string item in query)
                Console.WriteLine(item);

            Console.ReadLine();

linq를 공부하니 c#에 편리한점을 여러부분 발견하는것 같다.

- Client 소스 예.
using System;
using System.Runtime.Remoting.Channels.Ipc;
using System.Security.Permissions;
using dllobject;

public class Client
{
    [SecurityPermission(SecurityAction.Demand)]
    public static void Main(string[] args)
    {
        // Create the channel.
        IpcChannel channel = new IpcChannel();

        // Register the channel.
        System.Runtime.Remoting.Channels.ChannelServices.
            RegisterChannel(channel);

        // Register as client for remote object.
        System.Runtime.Remoting.WellKnownClientTypeEntry remoteType =
            new System.Runtime.Remoting.WellKnownClientTypeEntry(
                typeof(RemoteObject),
                "ipc://localhost:9090/RemoteObject.rem");
        System.Runtime.Remoting.RemotingConfiguration.
            RegisterWellKnownClientType(remoteType);

        // Create a message sink.
        string objectUri;
        System.Runtime.Remoting.Messaging.IMessageSink messageSink =
            channel.CreateMessageSink(
                "ipc://localhost:9090/RemoteObject.rem", null,
                out objectUri);
        Console.WriteLine("The URI of the message sink is {0}.",
            objectUri);
        if (messageSink != null)
        {
            Console.WriteLine("The type of the message sink is {0}.",
                messageSink.GetType().ToString());
        }

        // Create an instance of the remote object.
        RemoteObject service = new RemoteObject();

        // Invoke a method on the remote object.
        Console.WriteLine("The client is invoking the remote object.");
        while (true)
        {
            try
            {
                Console.WriteLine("The remote object has been called {0} times.",
                    service.GetCount());
            }
            catch
            {
                Console.WriteLine("channel fail...");
            }
        }
    }
}

- Server 소스 예제.
using System;
using System.Runtime.Remoting.Channels.Ipc;
using System.Security.Permissions;
using dllobject;

public class Server
{
    [SecurityPermission(SecurityAction.Demand)]
    public static void Main(string[] args)
    {
        try
        {
            // Create the server channel.
            IpcChannel serverChannel =
                new IpcChannel("localhost:9090");

            // Register the server channel.
            System.Runtime.Remoting.Channels.ChannelServices.RegisterChannel(
                serverChannel);

            // Show the name of the channel.
            Console.WriteLine("The name of the channel is {0}.",
                serverChannel.ChannelName);

            // Show the priority of the channel.
            Console.WriteLine("The priority of the channel is {0}.",
                serverChannel.ChannelPriority);

            // Show the URIs associated with the channel.
            System.Runtime.Remoting.Channels.ChannelDataStore channelData =
                (System.Runtime.Remoting.Channels.ChannelDataStore)
                serverChannel.ChannelData;
            foreach (string uri in channelData.ChannelUris)
            {
                Console.WriteLine("The channel URI is {0}.", uri);
            }

            // Expose an object for remote calls.
            System.Runtime.Remoting.RemotingConfiguration.
                RegisterWellKnownServiceType(
                    typeof(RemoteObject), "RemoteObject.rem",
                    System.Runtime.Remoting.WellKnownObjectMode.Singleton);

            // Parse the channel's URI.
            string[] urls = serverChannel.GetUrlsForUri("RemoteObject.rem");
            if (urls.Length > 0)
            {
                string objectUrl = urls[0];
                string objectUri;
                string channelUri = serverChannel.Parse(objectUrl, out objectUri);
                Console.WriteLine("The object URI is {0}.", objectUri);
                Console.WriteLine("The channel URI is {0}.", channelUri);
                Console.WriteLine("The object URL is {0}.", objectUrl);
            }
        }
        catch
        {
            Console.WriteLine("error....");
        }
        // Wait for the user prompt.
        Console.WriteLine("Press ENTER to exit the server.");
        Console.ReadLine();
        Console.WriteLine("The server is exiting.");
    }
}

- object 소스 예제.(DLL)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace dllobject
{
    public class RemoteObject : MarshalByRefObject
    {
        private int callCount = 0;

        public int GetCount()
        {
            Console.WriteLine("공유 안되구만...");
            callCount++;
            return (callCount);
        }
    }
}

좀전에 한 tcp와 비교해서 뭐가 틀린지 분석해 보자.
아 정말 프로세스 통신은 이해가 될까말까  하구만...


Client 소스 예제.(Client.EXE)

using System;
using ActMode;
using System.Runtime.Remoting; // RemotingConfiguration

namespace ActClient
{
    ///
    /// Summary description for Class1.
    ///
    class Class1
    {
        static void Main(string[] args)
        {
            // 원격 객체 프록시 생성
            //ActModeClass obj = (ActModeClass)Activator.GetObject(typeof(ActMode.ActModeClass), "http://localhost:1111/ActModeUri");
            //RemotingConfiguration.RegisterActivatedClientType(typeof(ActMode.ActModeClass), "http://localhost:1111/ActModeApp");
            //ActModeClass obj = new ActModeClass();
            ActModeClass obj = (ActModeClass)Activator.GetObject(typeof(ActMode.ActModeClass),
            "tcp://localhost:1111/ActModeUri");

            // 알림 메시지 표시
            Console.WriteLine("끝내려면 /quit 를 입력하세요.");

            while (true)
            {
                // 이용자로부터 문자열을 받는다
                string strText = Console.ReadLine();

                // "/quit" 문자열을 입력하면 프로그램을 종료시킨다
                if (strText == "/quit")
                    break;

                // 원격 객체의 메서드를 호출한다
                obj.AddString(strText);
            }
        }
    }
}

Server 소스 예제.(Server.EXE)
using System;

using System.Runtime.Remoting; // RemotingConfiguration
using System.Runtime.Remoting.Channels; // ChannelServices
using System.Runtime.Remoting.Channels.Tcp; // HttpChannel

namespace ActHosting
{
    ///
    /// Summary description for Class1.
    ///
    class Class1
    {
        [STAThread]
        static void Main(string[] args)
        {
            // HTTP 1111 port 채널을 등록한다
            //ChannelServices.RegisterChannel(new HttpChannel(1111));
            ChannelServices.RegisterChannel(new TcpChannel(1111));

            // ActMode 어셈블리의 ActModeClass를 Singleton 모드로 등록한다
//            RemotingConfiguration.RegisterWellKnownServiceType(typeof(ActMode.ActModeClass), "ActModeUri", WellKnownObjectMode.Singleton);
            //RemotingConfiguration.RegisterWellKnownServiceType(typeof(ActMode.ActModeClass), "ActModeUri", WellKnownObjectMode.SingleCall);
            //RemotingConfiguration.RegisterActivatedServiceType(typeof(ActMode.ActModeClass));
            //RemotingConfiguration.ApplicationName = "ActModeApp";

            // ActMode 어셈블리의 ActModeClass를 Singleton 모드로 등록한다
            RemotingConfiguration.RegisterWellKnownServiceType(typeof(ActMode.ActModeClass),
                "ActModeUri", WellKnownObjectMode.SingleCall);

 

            // 이용자 알림 메시지
            Console.WriteLine("호스팅 어플리케이션이 시작되었습니다.");
            Console.WriteLine("엔터키를 누르면 종료합니다.");

            // 대기 모드로 들어간다
            Console.ReadLine();
        }
    }
}

object 소스 예제.(DLL)
using System;

namespace ActMode
{
    ///
    /// Summary description for Class1.
    ///
    public class ActModeClass : MarshalByRefObject
    {
        string m_strString;

        public ActModeClass()
        {
            Console.WriteLine("생성자가 호출되었습니다.");
        }

        public void AddString(string strStr)
        {
            m_strString += strStr;

            Console.WriteLine(m_strString);
        }
    }
}

참조
- System.Runtime.Remoting 을 하시고
using 부분은 주의 깊게 봐 주십시요.
깊이있게 공부하실분은 channel 통신을 검색해서 공부하시기 바랍니다.



public byte[] esCapeChk(byte[] bMsg, int hNo, int tNo)
{
 int Head = hNo; // 검색할 Head 번지
 int Tail = tNo; // 검색할 Tail 변지
 byte[] bEscape = new byte[] { 0x7e, 0x7d }; // 삭제하고 싶은 Escape 문자를 추가
 ArrayList obj = new ArrayList(); // array List Create

 for (int i = 0; i < bMsg.Length; i++) // 수신받은 byte 전체를 arrylist에 저장
  obj.Add(bMsg[i]);

 for (int i = hNo; i < obj.Count - tNo; i++)
 {
  for (int j = 0; j < bEscape.Length; j++)
  {
   if (byte.Parse(obj[i].ToString()) == bEscape[j])
   {
    obj.RemoveAt(i);
    i = 0;
   }
  }
 }

 // escape를 제외한 개수로 배열을 새롭게 잡는다.
 byte[] newMsg = new byte[obj.Count];

 for (int i = 0; i < obj.Count; i++)
  newMsg[i] = (byte)(obj[i]);

 return newMsg;
}

이리저리 마음에 들진 않지만 서도...

뭐 이것저것 찾아보고 책에서 본것을 적어 본것 입니다.
특히 요즘 학생들의 질문요청이 쇄도하는 MFC와 C#에 특징에 대해서
알고 싶으신 분은 이문서를 다운 받으시면 충분한 답변이 되지 않을까 쉽네요

필요하시면 보시고, 댓글은 필수!

+ Recent posts