Ejemplo n.º 1
0
        /// <summary>
        /// 서브 폴더에서 입력한 이름의 file의 전체경로 제공
        /// 조건 : 해당 폴더들 내에서 file 이름은 단일 존재한다.
        /// </summary>
        /// <param name="targetPath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string findFileFromSubFolder(string targetPath, string fileName)
        {
            string res            = string.Empty;
            string scanedFileName = string.Empty;

            foreach (string f in System.IO.Directory.GetFiles(targetPath))
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint("File: " + f); // or some other file processing
                                                         // 파일 name 출력
#endif
                scanedFileName = System.IO.Path.GetFileName(f);
                if (scanedFileName.Equals(fileName))
                {
                    return(f);
                }
            }

            foreach (string d in System.IO.Directory.GetDirectories(targetPath))
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint("dir: " + d);             // 디렉토리 name 출력
#endif
                string resSub = findFileFromSubFolder(d, fileName); // recursive call to get files of directory
                if (!resSub.Equals(string.Empty))
                {
                    return(resSub);
                }
            }
            return(res);
        }
Ejemplo n.º 2
0
        public static string StartAsyncClient(string data, bool recvReply)
        {
            string result = string.Empty;

            // Connect to a remote device.
            try
            {
                // Establish the remote endpoint for the socket.
                // The name of the

                /*
                 *              // remote device is "host.contoso.com".
                 *              IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost");// ("host.contoso.com");
                 *              IPAddress ipAddress = ipHostInfo.AddressList[0];
                 */
                //현재 PC의 IP로 대체

                IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
                //IPAddress ipAddress = ipHostInfo.AddressList[0];  // ipv6
                IPAddress ipAddress = ipHostInfo.AddressList[1]; // ipv4

                IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

                // Create a TCP/IP socket.
                Socket client = new Socket(ipAddress.AddressFamily,
                                           SocketType.Stream, ProtocolType.Tcp);

                // Connect to the remote endpoint.
                client.BeginConnect(remoteEP,
                                    new AsyncCallback(ConnectCallback_client_async), client);
                connectDone_client_async.WaitOne();

                // Send test data to the remote device.
                Send_client_async(client, data);
                sendDone_client_async.WaitOne();

                if (recvReply == true)
                {
                    // Receive the response from the remote device.
                    Receive_client_async(client);
                    receiveDone_client_async.WaitOne();

                    // Write the response to the console.
#if DEBUG_PRINT_ENABLE
                    MyClass_Dprint.debugPrint("Response received : {0}", response); // 별도 recv thread
#endif
                    result = response;
                }
                // Release the socket.
                client.Shutdown(SocketShutdown.Both);
                client.Close();
            }
            catch (Exception e)
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(e.ToString());
#endif
            }
            return(result);
        }
Ejemplo n.º 3
0
        public static void test()
        {
            LinkedList <string> list = new LinkedList <string>();

            list.AddLast("ZApple");
            list.AddLast("CBanana");
            list.AddLast("Lemon");

            LinkedListNode <string> node    = list.Find("Banana");
            LinkedListNode <string> newNode = new LinkedListNode <string>("Grape");

            // 새 Grape 노드를 Banana 노드 뒤에 추가
            if (node != null)
            {
                list.AddAfter(node, newNode);
            }

            // 리스트 출력
#if DEBUG_PRINT_ENABLE
            list.ToList().ForEach(p => MyClass_Dprint.debugPrint(p));
#endif
            // Enumerator를 이용한 리스트 출력
            foreach (var m in list)
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(m);
#endif
            }
        }
Ejemplo n.º 4
0
        // run tcp socket server thread
        private static void serverThreaRun()
        {
#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("start listening");
#endif
            MyClass_Networks.StartServerListeningAsync();
        }
Ejemplo n.º 5
0
        // 2차원 배열 input 받아 sorting 후 2차원 배열로 output
        public static int[][] sortedArray(int [][] inData)
        {
            int ln_length  = inData.GetLength(0);    // 배열 크기
            int ln_length2 = inData[0].GetLength(0); // 배열 크기

            int[][] outArr = new int[ln_length][];
            for (int i = 0; i < inData.GetLength(0); i++)
            {
                outArr[i] = (int[])inData[i].Clone(); // array 복제 (반환되는 object를 array 타입케스팅하여 사용한다.)
            }

            Comparer <int> comparer = Comparer <int> .Default;

            // 람다식을 이용한 IComparer 구현
            Array.Sort <int[]>(inData, (x, y) => comparer.Compare(x[1], y[1])); // 1번째 배열로 오름차순 정렬
            //Array.Sort<int[]>(inData, (x, y) => comparer.Compare(x[0], y[0])); // 0번째 배열로 오름차순 정렬
            Array.Reverse(inData);                                              // 내림차순 정렬로 변환

            // 이중 for문으로 접근
            for (int i = 0; i < inData.GetLength(0); i++)
            {
                for (int ii = 0; ii < inData[0].GetLength(0); ii++)
                {
#if DEBUG_PRINT_ENABLE
                    MyClass_Dprint.debugPrint("sorted array>" + inData[i][ii]);
#endif
                }
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint("###");
#endif
            }
            return(inData);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// src string 내의 문자들이 target string 내에 순서와 상관없이 포함되어 있는지 확인 // coffee -> foecofee
        /// </summary>
        /// <param name="src"></param>
        /// <param name="target"></param>
        /// <param name="result"></param>
        /// <returns>0 매치됨, else 타겟에 몇개 문자 더 있음, -1 타겟에 문자 부족</returns>
        public static int checkCharsInString(string src, string target, ref string result)
        {
            int    res        = 0;
            string src_tmp    = src;
            string target_tmp = target;

            foreach (char c in src)                // 각 문자를 순서대로 비교
            {
                int index = target_tmp.IndexOf(c); // 일치하는 문자 위치 찾음
                if (index != -1)
                {
#if DEBUG_PRINT_ENABLE
                    MyClass_Dprint.debugPrint("match index:{0}", index);
#endif
                    target_tmp = target_tmp.Remove(index, 1); // 일치하는 문자 제거
                }
                else
                {
                    // not found char!!!!
                    return(-1); // 문자가 포함되지 않는다면 error return
                }
                //if (target_tmp.Contains(c))
                {
                }
            }
            result = target_tmp;        // 제거하고 남은 문자열 return
            if (target_tmp.Length != 0) // 남아있는 문자가 있다면 남은 문자 갯수 return
            {
                res = target_tmp.Length;
            }

            return(res); // 문자 수가 일치하면 return 0
        }
Ejemplo n.º 7
0
        // 파일 내 전체 텍스트를 한개의 string에 읽어온다
        public string readAllText(string filePath)
        {
            string text = System.IO.File.ReadAllText(filePath);

#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("readAllText : {0} ", text);
#endif
            return(text);
        }
Ejemplo n.º 8
0
        // 파일에서 한줄 읽어온다.
        public string readLine()
        {
            string res = file.ReadLine();

#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("ReadLine : {0} ", res);
#endif
            return(res);
        }
Ejemplo n.º 9
0
        private static void Send_Server(Socket handler, String data)
        {
            // Convert the string data to byte data using ASCII encoding.
            byte[] byteData = Encoding.ASCII.GetBytes(data);
#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("[Server] send data:[{0}] to client", data);
#endif
            // Begin sending the data to the remote device.
            handler.BeginSend(byteData, 0, byteData.Length, 0,
                              new AsyncCallback(SendCallback_Server), handler);
        }
Ejemplo n.º 10
0
     public static void StartServerWithThread()
     {
         // TCP 소켓 server/client sample //
         //MyClass_Networks.StartListeningAsync();
         // bool threadStop = false;
         /// var
         server_t = new System.Threading.Thread(() => serverThreaRun()); // 서버는 별도 thread에서 실행
         server_t.Start();                                               // 시작
 #if DEBUG_PRINT_ENABLE
         MyClass_Dprint.debugPrint("start StartClientSync");
 #endif
     }
Ejemplo n.º 11
0
        public static void StartServerListeningAsync()
        {
            // Data buffer for incoming data.
            byte[] bytes = new Byte[1024];
            // Establish the local endpoint for the socket.
            // The DNS name of the computer
            // running the listener is "host.contoso.com".
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            //IPAddress ipAddress = ipHostInfo.AddressList[0];  // ipv6
            IPAddress  ipAddress     = ipHostInfo.AddressList[1]; // ipv4
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);

            // Create a TCP/IP socket.
            Socket listener = new Socket(ipAddress.AddressFamily,
                                         SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and listen for incoming connections.
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(100);

                while (true)
                {
                    // Set the event to nonsignaled state.
                    allDone_server.Reset();

                    // Start an asynchronous socket to listen for connections.
#if DEBUG_PRINT_ENABLE
                    MyClass_Dprint.debugPrint("[Server] Waiting for a connection...");
#endif
                    listener.BeginAccept(
                        new AsyncCallback(AcceptCallback_server),
                        listener);

                    // Wait until a connection is made before continuing.
                    allDone_server.WaitOne();
                }
            }
            catch (Exception e)
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(e.ToString());
#endif
            }
#if DEBUG_PRINT_ENABLE
            //MyClass_Dprint.debugPrint("\nPress ENTER to continue...");
            MyClass_Dprint.debugPrint("[Server]  \nEnd server...");
#endif
            //			Console.Read();
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 클라이언트로 부터 recv 처리 callback
        /// </summary>
        /// <param name="ar"></param>
        public static void ReadCallback_server(IAsyncResult ar) // reveive file
        {
            String content = String.Empty;

            // Retrieve the state object and the handler socket
            // from the asynchronous state object.
            StateObject state   = (StateObject)ar.AsyncState;
            Socket      handler = state.workSocket;

            // Read data from the client socket.
            int bytesRead = handler.EndReceive(ar);

            if (bytesRead > 0)
            {
                // There  might be more data, so store the data received so far.
                // connection이 남아있으면 EOF까지 계속 append되지만, connection close시에 reset됨.
                state.sb.Append(Encoding.ASCII.GetString(
                                    state.buffer, 0, bytesRead));

                // Check for end-of-file tag. If it is not there, read
                // more data.
                content = state.sb.ToString();
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint("[server] Receved: {0}", content);
#endif
                if (content.IndexOf("<EOF>") > -1) // stream end DETECT ***
                //if(content.IndexOf("\r\n") > -1 || content.IndexOf("\n") > -1  || content.IndexOf("\r") > -1)
                {
                    // All the data has been read from the
                    // client. Display it on the console.
#if DEBUG_PRINT_ENABLE
                    MyClass_Dprint.debugPrint("[Server] Read {0} bytes from socket. \n Data : {1}", content.Length, content);
#endif
                    if (content.Contains("test")) // check 샘플
                    {
#if DEBUG_PRINT_ENABLE
                        MyClass_Dprint.debugPrint("[Server] test command received! ");
#endif
                    }
                    // 받은 메세지를 다시 client로 보낸다.
                    Send_Server(handler, content);
                }
                else // 연속된 data를 받아서 append하는 case.
                {
                    // Not all data received. Get more.
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                         new AsyncCallback(ReadCallback_server), state);
                }
            }
        }
Ejemplo n.º 13
0
        public void MyClass_Parse_And_Report4(string inputLog, string outputTxt)
        {
            // log 포맷 시간(19)#타입(2)#메시지코드(9)
            // 입력받은 text log 파일을 열어, #으로 split 한 후 각 type 별로 분리하고 카운팅한 결과를 output text에 저장
            MyClass_Files_Reader srcFile  = new MyClass_Files_Reader(inputLog);
            MyClass_Strings      strClass = new MyClass_Strings();
            string res = srcFile.readLine();             // 1 line read

            string[] line = srcFile.readLines(inputLog); // read all lines
            int      num  = line.Count();                // total count

#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("read lines:" + num);
#endif
            int            typeCount = strClass.countingAllTypes(line, delimiter, 1);
            string[]       logTypes  = strClass.getAllTypes(line, delimiter, 1);
            MyClass_Thread myThread  = new MyClass_Thread();
            // Example #4: Append new text to an existing file.
            // The using statement automatically flushes AND CLOSES the stream and calls
            // IDisposable.Dispose on the stream object.
            using (System.IO.StreamWriter outFile = new System.IO.StreamWriter(outputTxt, false))
            {
                foreach (string s in logTypes)
                {
                    //string[] data = strClass.StringSplit(s, delimiter);
                    int cnt = strClass.getCountOfType(line, delimiter, 1, s);
                    // 타입별 출력 파일 생성
                    MyClass_Files_Writer fileWriter = new MyClass_Files_Writer("TYPELOG_4_" + s + ".TXT");
                    // file writer 클래스에 thread safty하도록 lock 추가. (여러 thread에서 동시에 write의 경우 처리)


                    string[] strResult = strClass.getLinesOfType(line, delimiter, 1, s);// 입력된 타입에 해당되는 로그 만 추출한다.
                    foreach (string _line in strResult)
                    {
                        // 이부분 multi thread로 바꾼다.
#if DEBUG_PRINT_ENABLE
                        MyClass_Dprint.debugPrint("type: " + s);
                        MyClass_Dprint.debugPrint("line: " + _line);
#endif
                        myThread.StartConvertAndWrite(fileWriter, _line, delimiter, 2);
                    }
#if DEBUG_PRINT_ENABLE
                    MyClass_Dprint.debugPrint("type:" + s + " total num:" + cnt);
#endif
                    outFile.WriteLine(s + "#" + cnt);
                }
            }
        }
Ejemplo n.º 14
0
        public void MyClass_Parse_And_Report3(string inputLog, string outputTxt)
        {
            // log 포맷 시간(19)#타입(2)#메시지코드(9)
            // 입력받은 text log 파일을 열어, #으로 split 한 후 각 type 별로 분리하고 카운팅한 결과를 output text에 저장
            MyClass_Files_Reader srcFile  = new MyClass_Files_Reader(inputLog);
            MyClass_Strings      strClass = new MyClass_Strings();
            string res = srcFile.readLine();             // 1 line read

            string[] line = srcFile.readLines(inputLog); // read all lines
            int      num  = line.Count();                // total count

#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("read lines:" + num);
#endif
            int            typeCount = strClass.countingAllTypes(line, delimiter, 1);
            string[]       logTypes  = strClass.getAllTypes(line, delimiter, 1);
            MyClass_Thread myThread  = new MyClass_Thread();
            // Example #4: Append new text to an existing file.
            // The using statement automatically flushes AND CLOSES the stream and calls
            // IDisposable.Dispose on the stream object.
            using (System.IO.StreamWriter outFile =
                       new System.IO.StreamWriter(outputTxt, false))
            {
                foreach (string s in logTypes)
                {
                    //string[] data = strClass.StringSplit(s, delimiter);
                    int cnt = strClass.getCountOfType(line, delimiter, 1, s);

                    string[] strResult = strClass.getLinesOfType(line, delimiter, 1, s);// 타입별 로그를 추출한다.
                    foreach (string _line in strResult)
                    {
                        // convert and write to file
                        using (System.IO.StreamWriter file = new System.IO.StreamWriter("TYPELOG_3_" + s + ".TXT", false))
                        {
                            string convertedStr = strClass.convertStringMsg(_line, delimiter, 2);
                            {
                                file.WriteLine(convertedStr);
                            }
                        }
                    }
#if DEBUG_PRINT_ENABLE
                    MyClass_Dprint.debugPrint("type:" + s + " total num:" + cnt);
#endif
                    outFile.WriteLine(s + "#" + cnt);
                }
            }
        }
Ejemplo n.º 15
0
        // 폴더 내 전체 파일 스캔
        public static void TreeScan(string sDir)
        {
            foreach (string f in System.IO.Directory.GetFiles(sDir))
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint("File: " + f); // or some other file processing
                                                         // 파일 name 출력
#endif
            }

            foreach (string d in System.IO.Directory.GetDirectories(sDir))
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint("dir: " + d); // 디렉토리 name 출력
#endif
                TreeScan(d);                            // recursive call to get files of directory
            }
        }
Ejemplo n.º 16
0
        public void Test()
        {
            int[] coins = { 1, 10, 50, 100 };

            // CoinChangeCount c = new CoinChangeCount();
            // 1.  Recursive 방식 해결
            int ans = this.Count(coins, 4, 90);

#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("Count={0}", ans);
#endif
            // 2. 중간 결과를 저장(Memoization)하여 Lookup하는 방식 해결
            Dictionary <Tuple <int, int>, int> hash = new Dictionary <Tuple <int, int>, int>();
            ans = this.DPCount(coins, 4, 90, hash);
#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("DPCount={0}", ans);
#endif
        }
Ejemplo n.º 17
0
        /// <summary>
        /// 한줄 기록을 위한 WriteEntry 구현
        /// </summary>
        /// <param name="entry"></param>
        public void WriteEntry(string entry)
        {
            try
            {
                mutex.WaitOne();

                output.WriteLine("[" + DateTime.Now.ToString() + "]" + entry); // 로그 포맷~
                output.Flush();

                mutex.ReleaseMutex();
            }
            catch (Exception e)
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(e.Message);
#endif
            }
        }
Ejemplo n.º 18
0
        private static void StringCombination(string s, StringBuilder sb, int index)
        {
            for (int i = index; i < s.Length; i++)
            {
                // 1) 한 문자 추가
                sb.Append(s[i]);

                // 2) 구한 문자조합 출력
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(sb.ToString());
#endif
                // 3) 나머지 문자들에 대한 조합 구하기
                StringCombination(s, sb, i + 1);

                // 위의 1에서 추가한 문자 삭제
                sb.Remove(sb.Length - 1, 1);
            }
        }
Ejemplo n.º 19
0
        private static void Receive_client_async(Socket client)
        {
            try
            {
                // Create the state object.
                StateObject state = new StateObject();
                state.workSocket = client;

                // Begin receiving the data from the remote device.
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                    new AsyncCallback(ReceiveCallback_client_async), state);
            }
            catch (Exception e)
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(e.ToString());
#endif
            }
        }
Ejemplo n.º 20
0
        public int Count(int[] coins, int m, int n)
        {
            if (n == 0)
            {
                return(1);
            }
            if (n < 0)
            {
                return(0);
            }
            if (m <= 0)
            {
                return(0);
            }
#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("m:{0}, n:{1}", m, n);
#endif
            return(Count(coins, m - 1, n) + Count(coins, m, n - coins[m - 1]));
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 파일 전체를 읽어서 new line 타입을 최초에 detect 되는 타입으로 판단/return 한다.
        /// 2종류가 혼재되어 있지 않은 것을 전제한다.
        public string getNewLine()
        {
            //string[] readStr = this.readLines(mFilePath);
            string res = this.readAllText(mFilePath);

            if (res.Contains("\r\n"))
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(" new line with carriage return.");
#endif
                return("\r\n"); // 캐리지 리턴이 포함됨.
            }
            else if (res.Contains("\n"))
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(" new line");
#endif
                return("\n");
            }
            return(string.Empty);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// 지정된 폴더 내의 지정된 형식(filePrefix_x.x.x) 지정한 확장자의 파일 들을 스캔
        /// </summary>
        public static string[] scanFolderAndUpdate_Filelists(string targetPath, string extension)
        {
            List <string> strings = new List <string>();

            if (!System.IO.Directory.Exists(targetPath)) // 없으면
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint("error. tar folder not found. ");
#endif
                return(strings.ToArray());
            }
            string[] filePaths = System.IO.Directory.GetFiles(targetPath + "\\", "*." + extension);
            int      lengthA   = filePaths.Length;
            // 내림차순 정렬...
            var desc = from s in filePaths
                       orderby s descending
                       select s;
            foreach (string s in desc)
            {
                // get file name only
                string fileName = System.IO.Path.GetFileNameWithoutExtension(s);
                // 파일 이름에서 특정 패턴 매칭하여 버전등의 정보만 추출
                System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(fileName, @"filePrefix_([A-Za-z0-9\-\.]+)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                if (match.Success)
                {
                    // Finally, we get the Group value and display item
                    string key = match.Groups[1].Value;
                    // add to string list.
                    strings.Add(key);
                }
            }
            if (strings.Count <= 0)
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint("[scanFolder] error. no file in dir. ");
#endif
                return(strings.ToArray());
            }
            return(strings.ToArray());
        }
Ejemplo n.º 23
0
        private static void SendCallback_Server(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket handler = (Socket)ar.AsyncState;

                // Complete sending the data to the remote device.
                int bytesSent = handler.EndSend(ar);
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint("Sent {0} bytes to client.", bytesSent);
#endif
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }
            catch (Exception e)
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint("[Server] {0}", e.ToString());
#endif
            }
        }
Ejemplo n.º 24
0
        private static void ReceiveCallback_client_async(IAsyncResult ar)
        {
            try
            {
                // Retrieve the state object and the client socket
                // from the asynchronous state object.
                StateObject state  = (StateObject)ar.AsyncState;
                Socket      client = state.workSocket;

                // Read data from the remote device.
                int bytesRead = client.EndReceive(ar);

                if (bytesRead > 0)
                {
                    // There might be more data, so store the data received so far.
                    state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                    // Get the rest of the data.
                    client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                        new AsyncCallback(ReceiveCallback_client_async), state);
                }
                else
                {
                    // All the data has arrived; put it in response.
                    if (state.sb.Length > 1)
                    {
                        response = state.sb.ToString();
                    }
                    // Signal that all bytes have been received.
                    receiveDone_client_async.Set();
                }
            }
            catch (Exception e)
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(e.ToString());
#endif
            }
        }
Ejemplo n.º 25
0
        private static void SendCallback_client_async(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket client = (Socket)ar.AsyncState;

                // Complete sending the data to the remote device.
                int bytesSent = client.EndSend(ar);
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint("Sent {0} bytes to server.", bytesSent);
#endif

                // Signal that all bytes have been sent.
                sendDone_client_async.Set();
            }
            catch (Exception e)
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(e.ToString());
#endif
            }
        }
Ejemplo n.º 26
0
        private static void ConnectCallback_client_async(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket client = (Socket)ar.AsyncState;

                // Complete the connection.
                client.EndConnect(ar);
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint("Socket connected to {0}",
                                          client.RemoteEndPoint.ToString());
#endif
                // Signal that the connection has been made.
                connectDone_client_async.Set();
            }
            catch (Exception e)
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(e.ToString());
#endif
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// 목록 전체 기록을 위한 WriteEntry 구현
        /// </summary>
        /// <param name="entry"></param>
        public void WriteEntry(System.Collections.ArrayList entry)
        {
            try
            {
                mutex.WaitOne();

                System.Collections.IEnumerator line = entry.GetEnumerator();
                while (line.MoveNext())
                {
                    output.WriteLine(line.Current);
                }
                output.WriteLine();
                output.Flush();

                mutex.ReleaseMutex();
            }
            catch (Exception e)
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(e.Message);
#endif
            }
        }
Ejemplo n.º 28
0
        public void MyClass_Parse_And_Report2(string inputLog, string outputTxt)
        {
            // log 포맷 시간(19)#타입(2)#메시지코드(9)
            // 입력받은 text log 파일을 열어, #으로 split 한 후 각 type 별로 분리하고 카운팅한 결과를 output text에 저장
            MyClass_Files_Reader srcFile  = new MyClass_Files_Reader(inputLog);
            MyClass_Strings      strClass = new MyClass_Strings();
            string res = srcFile.readLine();             // 1 line read

            string[] line = srcFile.readLines(inputLog); // read all lines
            int      num  = line.Count();                // total count

#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("read lines:" + num);
#endif
            int      typeCount = strClass.countingAllTypes(line, delimiter, 1);
            string[] logTypes  = strClass.getAllTypes(line, delimiter, 1);

            // Example #4: Append new text to an existing file.
            // The using statement automatically flushes AND CLOSES the stream and calls
            // IDisposable.Dispose on the stream object.
            using (System.IO.StreamWriter outFile =
                       new System.IO.StreamWriter(outputTxt, true))
            {
                //outFile.WriteLine("Fourth line");
                // scan types
                foreach (string s in logTypes)
                {
                    //string[] data = strClass.StringSplit(s, delimiter);
                    int cnt = strClass.getCountOfType(line, delimiter, 1, s);
#if DEBUG_PRINT_ENABLE
                    MyClass_Dprint.debugPrint("type:" + s + " total num:" + cnt);
#endif
                    outFile.WriteLine(s + "#" + cnt);
                }
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// FileLogger 생성자, Application 실행 디렉토리/log 에 파일을 생성
        /// </summary>
        /// <param name="name">file path</param>
        public MyClass_Logger(string name)
        {
#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));
            MyClass_Dprint.debugPrint(System.AppDomain.CurrentDomain.BaseDirectory);
            MyClass_Dprint.debugPrint(System.Environment.CurrentDirectory);
            MyClass_Dprint.debugPrint(System.IO.Directory.GetCurrentDirectory());
            MyClass_Dprint.debugPrint(Environment.CurrentDirectory);
#endif
            //To get the location the assembly normally resides on disk or the install directory
            string _path = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
            //once you have the path you get the directory with:
            var directory = System.IO.Path.GetDirectoryName(_path);
            // string absPath = new Uri(directory).AbsolutePath;
            directory = directory.Replace(@"file:\", "");
            string path     = directory + "\\log\\";
            string fullname = path + name;

            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
            output = new System.IO.StreamWriter(fullname, true);
        }
Ejemplo n.º 30
0
        public void run_Test()
        {
#if false
            // 도서관리 sample
            MyClass_BookManager bm = new MyClass_BookManager();
            bm.Run();
#endif
#if false
            // 100의 bitcoins 전송 sample //
            List <MyClassBlockChain> blockchain = new List <MyClassBlockChain>();
            // Genesis block
            string[] transactions = { "Jone Sent 100 Bitcoins to Bob." };
            // 최초 노드 : genesisBlock
            myClassBlockChainHeader blockheader  = new myClassBlockChainHeader(null, transactions);
            MyClassBlockChain       genesisBlock = new MyClassBlockChain(blockheader, transactions);
            Console.WriteLine("Block Hash : {0}", genesisBlock.getBlockHash());

            Stopwatch         stopw         = new Stopwatch();//시간 측정 클래스
            MyClassBlockChain previousBlock = genesisBlock;
            for (int i = 0; i < 5; i++)
            {
                myClassBlockChainHeader secondBlockheader = new myClassBlockChainHeader(Encoding.UTF8.GetBytes(previousBlock.getBlockHash()), transactions);
                MyClassBlockChain       nextBlock         = new MyClassBlockChain(secondBlockheader, transactions);
                stopw.Start();
                int count = secondBlockheader.ProofOfWorkCount();
                stopw.Stop();
                Console.WriteLine("{0} th Block Hash : {1}", i.ToString(), nextBlock.getBlockHash());
                Console.WriteLine("   └ COUNT of Proof of Work : {0} th loop", count);
                Console.WriteLine("   └ Delay : {0} millisecond", stopw.ElapsedMilliseconds);
                previousBlock = nextBlock;
                stopw.Reset();
            }
#endif

            // Array to List
            int[]      ints = new[] { 10, 20, 10, 34, 113 };
            List <int> lst  = ints.OfType <int>().ToList();
            lst.AddRange(new int[] { 10, 20, 10, 34, 113 });
            // List to Array
            int [] intsArray = lst.ToArray();

            //중복되지 않는 첫번째 문자 구하기 // dictionary 사용
            string s  = "abcabdefe";
            char   ch = MyClass_Strings.GetFirstChar(s.ToCharArray());
#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint(ch);
#endif

            // 문자열 내 문자로 가능한 조합 구하기
            MyClass_Strings.getStringCombination("ABC");

            // string 내 패턴 스트링 카운팅
            string sampleData = "asdfkk;lkasldfajsdlkfj999kajsdlfkjasdlfkj9999kljflaskdflkajsdlfkjasdlkfj999lkajsdlfkjasldfkja999";
            // 정규식 매칭 확인 + count
            //int countResult = System.Text.RegularExpressions.Regex.Matches(sampleData, "999").Count;
            int   countResult = MyClass_Strings.countMatches(sampleData, "999");
            Match matchRes    = Regex.Match(sampleData, "999");
            // recursive하게 sub folder에서 유일한 file 찾기 예
            string fullPath = MyClass_Files.findFileFromSubFolder(".", "test.txt");

            // 스트링내 캐릭터 조합 비교 예
            string res  = string.Empty;
            int    ress = MyClass_Strings.checkCharsInString("coffee", "fofeefac", ref res);

            // 라인브레이크 사용자설정 예  // append mode on/off 예
            MyClass_Files_Writer fileWriter = new MyClass_Files_Writer("fileWrite.TXT", false);
            fileWriter.customNewLine = "\r\n";
            fileWriter.WriteToFile("asdfasdfasdfasdf");
            fileWriter.WriteToFile("asdfasdfasdfasdf");
            fileWriter.WriteToFile("asdfasdfasdfasdf");
            // 소스의 라인브레이크 디텍션 예
            MyClass_Files_Reader reader = new MyClass_Files_Reader("fileWrite.TXT");
            string getNewLineChar       = reader.getNewLine(); // newLine 형식 읽어와서 file writer의 customNewLine에도 맞춰주면 된다.

            // 암호화 예
            string str_test  = "3#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            string str_Enc   = MyClass_Security.CaesarCipherEncrypt(str_test, 20);
            string str_test2 = "21#abcdefghijklmnopqrstuvwxyz";
            string str_Enc2  = MyClass_Security.CaesarCipherEncrypt(str_test2, 20);

            //


            // 메서드로 바꿀것
            // ABC 부품을 갖고 A7 B7 C7이 순서대로 오면 제품 조립 ok
            // 총 완성 제품 counting
            string str_Product_struct   = "A2B3A7B7C7B2C7A9B4A9B8C7A2B7C9";
            char[] array_Product_struct = str_Product_struct.ToCharArray();
            int    status            = 0; //1:A ok, 2:B ok, 3:C ok
            int    totalProductCount = 0;
            for (int i = 0; i < array_Product_struct.Length; i = i + 2)
            {
                string num = string.Empty;
                num += array_Product_struct[i + 1];
                int part_count = Convert.ToInt32(num);
                //int level2 = Convert.ToInt32("-1024");
                //int level = (int)Char.GetNumericValue(array_Product_struct[i + 1]);//Convert.ToInt32(array_Product_struct[i + 1]);
                if (array_Product_struct[i] == 'A')
                {
                    if (part_count >= 7)
                    {
                        status = 1;
                    }
                    else
                    {
                        status = 0;
                    }
                }
                if (array_Product_struct[i] == 'B' && status == 1)
                {
                    if (part_count >= 7)
                    {
                        status = 2;
                    }
                    else
                    {
                        status = 0;
                    }
                }
                if (array_Product_struct[i] == 'C' && status == 2)
                {
                    if (part_count >= 7)
                    {
                        //status = 3;
                        // count up
                        status = 0;
                        totalProductCount++;
                    }
                    else
                    {
                        status = 0;
                    }
                }
            }
#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("totalProductCount: " + totalProductCount);
#endif

            // 구조체 타입 list의 정렬 예
            //MyClass_list_sort<int> lSortTest = new MyClass_list_sort<int>();
            MyClass_list_sort.test();
            //MyClass_array_sort sortTest = new MyClass_array_sort();
            MyClass_array_sort.test();

            // 헤시맵을 이용한 정렬 TODO
            MyClass_hashMap hashTest = new MyClass_hashMap();  // TODO...
            hashTest.test();

            // 링크드리스트 사용 예
            //MyClass_linkedList list = new MyClass_linkedList();
            MyClass_linkedList.test();

            // 동전바꿈 예
            MyClass_coinChangeCount cnt = new MyClass_coinChangeCount();
            cnt.Test();


            // MyClass_Parse_Log parse = new MyClass_Parse_Log('#'); // delimitor
            // 문제 sample //
            // parse.MyClass_Parse_And_Report1("LOGFILE_A.TXT", "REPORT_1.TXT");            // 문제 2
            //parse.MyClass_Parse_And_Report2("LOGFILE_B.TXT", "REPORT_2.TXT");
            //parse.MyClass_Parse_And_Report3("LOGFILE_B.TXT", "REPORT_3.TXT");
            //parse.MyClass_Parse_And_Report4("LOGFILE_B.TXT", "REPORT_4.TXT");


            // 암호/복호화 sample //
            String originalText = "plain text";
            String key          = "key";
            String en           = MyClass_Security.Encrypt(originalText, key);
            String de           = MyClass_Security.Decrypt(en, key);
#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("Original Text is " + originalText);
            MyClass_Dprint.debugPrint("Encrypted Text is " + en);
            MyClass_Dprint.debugPrint("Decrypted Text is " + de);
#endif
            MyClass_Networks.StartServerWithThread();
            //string testSend = MyClass_Networks.StartClientSync("1111111");
            string testSend2 = MyClass_Networks.StartClientSync("send data 111111 ", false);
            //testSend2 = MyClass_Networks.StartClientSync("222222 ", false);
            testSend2 = MyClass_Networks.StartClientSync("test <EOF>", true);
#if DEBUG_PRINT_ENABLE
            // MyClass_Dprint.debugPrint("start StartAsyncClient");
#endif
            //MyClass_Networks.StartAsyncClient("test <EOF>");
            //MyClass_Networks.StartAsyncClient("<EOF>");
#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("abort socket server thread");
#endif

            MyClass_Networks.StopServerWithThread();

            // 폴더 스캔 샘플 //
            MyClass_Files.TreeScan(".\\..");
            // 지정한 확장자를 가진 파일을 폴더내에서 찾아 list로 update
            string[] resultt = MyClass_Files.scanFolderAndUpdate_Filelists(".", "cs");

            // 로그파일 쓰기 예 //
            MyClass_Logger log = new MyClass_Logger("restLog.txt");
            log.WriteEntry("TTTTTTTTTTTTTTTTTTTTTTTTT");

            // 링버퍼 샘플 //
            MyClass_RandomData rndData = new MyClass_RandomData();
            rndData.rnd = new Random();                          // random 초기화..
            var data = rndData.GenerateRandomData(10);           // 100개의 random 데이터 생성
            // MyClass_CircularBuffer<타입>(갯수)
            var buffer = new MyClass_CircularBuffer <byte>(100); // 링버퍼 생성
            buffer.Put(data);                                    // 10 byte push
            data = rndData.GenerateRandomData(10);
            buffer.Put(data);
            //TestTools.UnitTesting.CollectionAssert.AreEqual(data, buffer.ToArray());
            var ret = new byte[10]; //[buffer.Size];
            buffer.Get(ret);
            buffer.Get(ret);        // buffer size만큼 get

            //CollectionAssert.AreEqual(data, ret);
            //Assert.IsTrue(buffer.Size == 0);

            int test = 2;
        }