Egloos | Log-in


[C#] 간단한 버블 소트 작성하기

정수 데이터를 사용한 간단한 Bubble sorting 프로그램 예제를 작성해 본다.
버블 소트는 n 개의 데이터에 대하여 이중 for loop를 한 번 실행해 주면 된다.
최고 효율의 소팅 알고리즘은 아니지만, 코드가 간단하기 때문에 많이 사용한다.

<Sort.cs> - C# express 2008의 콘솔응용프로그램
============================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; // 사용자 추가
using System.Collections; // 사용자 추가

namespace Sort
{
    class Program
    {
        static void Main(string[] args)
        {
            // 파일에서 데이터 읽기
            StreamReader fi = new StreamReader("d:\\input.txt");

            ArrayList nums_array = new ArrayList();

            // 입력 데이터의 갯수를 모르기 때문에, 읽어서 ArrayList에 저장한다.
            string line1 = fi.ReadLine();

            while (line1!=null)
            {
                nums_array.Add(Convert.ToInt32(line1));
                line1 = fi.ReadLine();
            }

            // ArrayList를 정수 array로 변환

            int[] nums = (int[])nums_array.ToArray(typeof(int));
            int temp;
            // 버블 소트

            for (int i=0;i<nums.Length-1; i++)
                for (int j=i+1; j<nums.Length; j++)
                    if (nums[i]>nums[j]) // 오름차순 정렬
                    {
                        temp = nums[i];
                        nums[i] = nums[j];
                        nums[j] = temp;
                    }

            fi.Close();

            // 콘솔(도스창)으로 출력

            for (int i=0; i<nums.Length; i++)
                Console.WriteLine("{0}", nums[i]);
            Console.ReadKey();

        }
    }
}
===============================================================

<input.txt> 입력 데이터
==========================
58
35
61
79
39
11
7
97
43
83
55
14
48
==========================

<출력 화면>

by 헤이즐넛 | 2009/09/18 19:05 | 프로그래밍 | 트랙백 | 덧글(0)

[C#] 문자열이 정수인지 확인하기

입력 받은 문자열이 정수(또는 실수)인지 확인하려면
아래와 같이 간단히 try 문을 써서 사용할 수 있다.

문자열이 정수로 변환 가능하면 true, 실패하면 false를 리턴한다.
=========================================
        private bool IsNumeric(string str)
        {
            int i;
            try
            {
                i = Convert.ToInt32(str);
            }
            catch
            {
                return false;
            }

            return true;
        }

by 헤이즐넛 | 2009/09/17 13:28 | 프로그래밍 | 트랙백 | 덧글(0)

[C#] Process를 이용한 외부 프로그램 실행하기 (2)

이전 글에서 C#에서 Process()를 사용한 외부 프로그램 실행을 소개하였다.

외부 프로그램 실행이 끝날때까지 기다리기 위해서 Thread.Sleep()을 사용할 경우,
그 프로그램이 끝날 때까지 주 프로그램은 대기 상태가 되므로..
자식 프로그램의 실행이 상당히 오래걸리는 경우에는 Timer를 사용한다.

아래는 타이머를 사용한 예제이다.
먼저 윈도우 도구상자에서 Timer 컨트롤을 폼에 끌어다 놓는다.
=============================================================
using System.Diagnostics; // Process 사용
using System.Threading;   // Timer 사용

   class RunTest
   {
        bool eventhandler1 = false;

        public void RunAbaqus(string job)
        {
            try
            {
                //eventhandler1 = false;

                Process pr1 = new Process();
                pr1.StartInfo.FileName = "abaqus"; // 프로그램 실행 커맨드
                pr1.StartInfo.Arguments = "cae noGUI=" + job; // 프로그램 실행용 추가 인자

                pr1.StartInfo.WindowStyle = ProcessWindowStyle.Normal;  // dos command 창을 열고 실행한다.
                // pr1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;  // dos command 창을 열지않고 실행한다.

                pr1.EnableRaisingEvents = true; 
                pr1.Exited += new EventHandler(cmdProcess_Exited); // 프로그램 종료 이벤트에 cmdProcess_Exited 메소드 추가

                eventhandler1 = false;

                pr1.Start();

                statusLabel1.Text = "report 파일을 생성중입니다.";
                timer1.Interval = 1000;
                timer1.Enabled = true;

                return 1;
            }
            catch
            {
                return -1; //"An error occurred running exe program
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (eventhandler1)
            {
                MessageBox.Show("외부 프로그램 실행이 종료되었습니다.");
                eventhandler1 = false;
                timer1.Enabled = false;
            }
        }

        private void cmdProcess_Exited(object sender, System.EventArgs e)
        {
            eventhandler1 = true;
        }

        private void cmdProcess_Exited(object sender, System.EventArgs e)
        {
            eventhandler1 = true; // 외부 프로그램이 종료되면 eventhandler1 전역변수를 true로 전환
        }
    }

by 헤이즐넛 | 2009/09/04 14:50 | 프로그래밍 | 트랙백 | 덧글(0)

[C#] 폼의 특정 컨트롤에 디폴트 포커스 주기

윈도우 폼의 특정 컨트롤에 디폴트 포커스(default focus)를 주기 위해서는
Select() 메소드를 사용한다.

아래는 텍스트 박스(textID)에 디폴트(즉, 초기의) 포커스를 주기 위한 예제이다.

===============================
textID.Select();  // 단순히 포커스만 설정

textID.Select(0,2); // 아래와 같이 입력된 문자의 처음(0)부터 2문자를 선택한 상태가 됨
===============================








위에서 단순히 textID.Select();를 사용하면,
텍스트 박스에 자동 입력된 글자가 있는 경우에  입력된 글자가 미리 선택된 상태가 된다.
글자 선택없이, 단지 커서만 위치하게 하려면..
===================================
textID.Select(textID.Text.Length,0);
===================================
와 같이 사용한다.

by 헤이즐넛 | 2009/09/03 16:07 | 프로그래밍 | 트랙백 | 덧글(0)

[SQL] 사용자 비밀번호를 암호화하여 저장하고 비교하기

신규 등록하는 회원의 사용자 비밀번호를 char 또는 varchar로 그대로 저장하면,
후에 select 문을 사용하여 저장된 비밀번호를 조회할 수 있다.

insert 문으로 저장시에 아래의 pwdencrypt() SQL 내장함수를 쓰면 사용자 비밀번호를 암호화하여 저장한다.
대신, 나중에 로그인 처리를 할 때에 이렇게 암호화된 비밀번호를 조회할 수 없기 때문에, SQL,에서는 pwdcompare() 함수를 함께 제공한다.

0. ASP.NET web.config 파일에 connectionString 저장
========================================
<?xml version="1.0"?>
<configuration>
 <appSettings>
 </appSettings>
 <!-- ConfigurationSettings.AppSettings["con_str"] -->
 <connectionStrings>
        <add name="con_str" connectionString="server=mycom; database=mydb; user id = sa; password=000" providerName="System.Data.SqlClient"/>
        <!-- System.Web.Configuration.WebConfigurationManager.ConnectionStrings["con_str"].ConnectionString -->
    </connectionStrings>
========================================

1. 사용자 아이디와 비밀번호를 입력하기
=======================================
                string m_id = textUserid.Text.ToLower(); // id를 모두 소문자로 변환
                string m_pwd = textPasswd.Text; // 비밀번호
                string m_name = textName.Text; // 사용자 이름

                SqlConnection con = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["con_str"].ConnectionString); // web.config에 설정한 DB 연결문
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandText = "INSERT INTO users (userid, passwd, name1) VALUES (@id,convert(varbinary(255),pwdencrypt(@pwd)))";

                cmd.Parameters.Add("@id", SqlDbType.VarChar, 20);
                cmd.Parameters.Add("@pwd", SqlDbType.VarChar, 50);
                cmd.Parameters.Add("@name", SqlDbType.VarChar, 20);
                cmd.Parameters["@id"].Value = m_id;
                cmd.Parameters["@pwd"].Value = m_pwd;
                cmd.Parameters["@name"].Value = m_name;

                try
                {
                    con.Open();

                    if (cmd.ExecuteNonQuery() > 0)
                        labelMsg1.Text = "New account is created : " + m_id + "(" + m_name + ")";
                }
                catch (SqlException ex)
                {
                    labelMsg1.Text = "SQL exception error (" + ex.Number + "): " + ex.Message;
                }
                catch (InvalidOperationException ex)
                {
                    labelMsg1.Text = "Invalid operation error : " + ex.Message;
                }
                catch (Exception ex)
                {
                    labelMsg1.Text = "Exception error : " + ex.Message;
                }
                finally
                {
                    con.Close();
                }
========================================

2. 사용자 로그인시에 아이디와 비밀번호 확인하기
=======================================
        private bool Authenticate(string id, string pwd)
        {
            bool res = false;

            SqlConnection con = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["con_str"].ConnectionString);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "select pwdcompare(@pwd,passwd), name1, userlevel from users where userid = @id";

            cmd.Parameters.Add("@id", SqlDbType.VarChar, 20);
            cmd.Parameters.Add("@pwd", SqlDbType.VarChar, 50);
            cmd.Parameters["@id"].Value = id;
            cmd.Parameters["@pwd"].Value = pwd;
            SqlDataReader reader = null;

            try
            {
                con.Open();

                reader = cmd.ExecuteReader();
                reader.Read();
                if (Convert.ToInt32(reader[0])>0)
                {
                    Session["name"] = reader[1];
                    Session["userlevel"] = reader[2];
                    Session["user_id"] = id;


                    res = true;
                }
                else
                    labelMsg2.Text = "Invalid User Id or Password";
            }
            catch (Exception ex)
            {
                labelMsg2.Text = ex.Message;
            }
            finally
            {
                if (reader != null) reader.Close();
                con.Close();
            }
            return res;
        }

by 헤이즐넛 | 2009/08/26 23:32 | 프로그래밍 | 트랙백 | 덧글(0)

◀ 이전 페이지          다음 페이지 ▶