윈폼 어플리케이션이 구동될 때, 메인폼의 startup Event는 다음 순서로 일어난다.

  • ControlHandleCreated
  • ControlBindingContextChanged
  • FormLoad
  • ControlVisibleChanged
  • FormActivated
  • FormShown

어플리케이션이 닫힐 때, 메인폼의 shutdown Event는 다음 순서로 일어난다.

  • FormClosing
  • FormFormClosing
  • FormClosed
  • FormFormClosed
  • FormDeactivate


[MSDN]Order of Events in Windows Forms 참조
Posted by lI헐헐Il
,

IP로 hostname 찾기

IT/IT 일반 2013. 4. 10. 15:39

cmd 창에서

nbtstat -A ***.***.***.***

 

위 명령어로 IP 주소로 컴퓨터이름을 얻어올 수 있다. 다만 netbios 기반으로 돌기 때문에 네트워크 단위를 넘어설 수 없다.

Posted by lI헐헐Il
,
FileStream fs = File.OpenRead(filePath);

MemoryStream ms = new MemoryStream();
ms.SetLength(fs.Length);

fs.Read(ms.GetBuffer(), 0, (int)ms.Length);
fs.Close();
			

fs = File.OpenWrite(filePath + ".bak");
ms.WriteTo(fs);

fs.Close();
ms.Close();
fs = null; ms = null;

Posted by lI헐헐Il
,
<?xml version="1.0" encoding="utf-8" ?>
<Persons>
  <Person name="John Smith">
    <Age>30</Age>
    <Gender>Male</Gender>
  </Person>
  <Person name="Mike Folley">
    <Age>25</Age>
    <Gender>Male</Gender>
  </Person>
  <Person name="Lisa Carter">
    <Age>22</Age>
    <Gender>Female</Gender>
  </Person>
  <Person name="Jerry Frost">
    <Age>27</Age>
    <Gender>Male</Gender>
  </Person>
  <Person name="Adam Wong">
    <Age>35</Age>
    <Gender>Male</Gender>
  </Person>
</Persons>

 XPath Query

Description 

Selects the current node. 

.. 

Selects the parent of the current node. 

Selects all the child of the current node. 

Selects the root nodes. 

// 

Selects nodes from the current node that match the selection expressions no matter where they are. 

 //*

Selects all elements in the document. 

 /element

Selects the root element named element. Staring a path with a / means you are using an absolute path to an element. 

 /element/*

Selects all the child of the root element. 

 element/*

Selects all the child nodes of a child element. 

 element/child

Selects the child elements which are a child of a sprecified child element of the current node. 

 //element

Selects all elements with the specified name regardless of where they are in the document. 

element/child 

Selects the child elements which are a child of a specified child element of the current node. 

 //element

Selects all elements with the specified name regardless if where they are in the document.

 element//child

Selects all child elements of the parent regardless of where they are in the document. 

 @attribute

Selects an attribute of the current node where attribute is the name of the attribute. 

 //@attribute

Selects all the attributes specified by its name regardless of where they are in the document. 

 @*

Selects all attribute of the current node. 

 element[i]

Selects an element with the specified element name and the specified index. 

 text()

Selects the text of all the child nodes of the current element. 

 //text()

Selects text of every element in the document. 

 //element/text()

Selects the text of all the matching elements. 

 //element[name='value']

Selects the text of all the matching elements. 

 //elements[@att='value']

Selects all elements with the specified attribute having the specified value. 

 


FileStream fs = new FileStream("...경로", FileMode.Open, FileAccess.Read);
XmlDocument xDoc = new XmlDocument();
xDoc.Load(fs);
XmlNodeList xNodes = xDoc.SelectNodes("/Persons/Person"); // SelectNodes의 xPath 사용법을 알아둘 것!!

if(xNodes[0] != null) // SelectNodes 후에는 선택해온 값이 있는지 확인부터 할것. 
{                           //  아닌 경우 NullReference 예외가 발생할 수 있음.
          // To do:
         string strTmp = xNodes[0].Attribute["name"].Value;
}

fs.Close(); fs = null;
Posted by lI헐헐Il
,

JOIN UPDATE / DELETE

IT/SQL 2013. 3. 18. 14:36
-- JOIN UPDATE
UPDATE ORDERS
SET OrderDate = getdate()
FROM ORDERS A INNER JOIN [ORDER DETAILS] B ON A.ORDERID = B.ORDERID
WHERE B.DISCOUNT > 0.1


-- JOIN DELETE
DELETE TABLE_MAIN
FROM TABLE_MAIN A
INNER JOIN TABLE_JOIN B ON A.SEQNUM = B.SEQNUM AND B.PROGBN = 'Y'

조인을 이용한 UPDATE/DELETE 구문이다.
Posted by lI헐헐Il
,

1) NOLOCK (= READUNCOMMITTED)

MS-SQL 서버의 경우 데이터의 일관성을 보장하기 위해 SELECT 작업을 할떄도 공유잠금(S)을 설정합니다.

이러한 경우 SELECT 하는 동안에는 동일한 대상(행,페이지, 테이블 등)에 다른 spid에서 배타적 잠금(X)을 설정할 수 없습니다.

 

하지만, 이러한 특성 때문에 동시사용자가 많은 환경에서 차단(Blocking) 현상이 발생할 가능성이 있습니다.

 

즉,

1) 배타적 잠금이 걸린 대상에 대해서는 공유잠금(S)을 설정할 수 없기 때문에 차단이 발생하는 경우와,

2) 공유잠금이 걸린 대상에 배타적 잠금을 설정하는 경우가 모두 차단현상이 발생하는 문제가 발생합니다.

 

이를 해결하기 위해 SELECT 쿼리의 FROM Clause 다음의 각 테이블에 NOLOCK 옵션을 사용하게 되면 SELECT 쿼리를 할 때 공유잠금을 설정하지 않고 데이터를 읽게 됩니다. 이를 통해, 위의 두 가지 경우 차단현상이 발생하지 않고 작업을 수행할 수 있습니다.

 

2) ROWLOCK

SQL Server는 기본적으로 행 단위 잠금을 사용합니다. 다만, 내부적인 기준에 따라 행 단위 잠금보다 더 상위단위(페이지, 테이블) 대상에 대해서 잠금을 설정해야 한다면 페이지잠금, 테이블잠금을 자동적으로 승격하여 사용하게 됩니다. 이러한 경우, 특별하게 사용자가 이를 통제하여 행단위잠금을 강제하기 위해서 사용하는 옵션입니다. 이 옵션은 채번과 같은 매우 고유한 업무에 대해서만 제한적으로 사용되어야 합니다.

 

3)UPDLOCK

 

UPDLOCK은 SELECT하는 대상에 대해 곧바로 배타적잠금을 설정할 예정인 경우, SELECT 하는 대상에 다른 세션에서 배타적 잠금을 설정하지 못하도록 통제하기 위해 사용합니다.

 

즉,

1) spid 51 : SELECT * FROM 테이블

2) spid 52 : UPDATE 테이블 SET ...

3) spid 51 : UPDATE 테이블 SET ...

 

이러한 경우 51번의 업데이트 작업은 52번의 업데이트 작업이 완료될 때까지 차단되고 대기해야 합니다.

 

이때,

1) spid 51 : SELECT * FROM 테이블 WITH (UPDLOCK)

2) spid 52 : UPDATE 테이블 SET ...

3) spid 51 : UPDATE 테이블 SET ...

 

를 사용하면, 52번 업데이트 작업이 51번에서 설정된 UPDLOCK으로 인해 차단되고, 3번 UPDATE 작업은 계속하여 진행할 수 있게 됩니다.

 

이러한 잠금과 관련된 옵션은 데이터 일관성과 병행성이라는 두 마리 토끼를 잡기 위해 노력하면서, 데드락과 같은 문제가 발생하지 않도록 하기 위해, 각 업무환경에 따라 매우 주의하여 사용되어져야 합니다.

Posted by lI헐헐Il
,
using System;
using System.Runtime.InteropServices;
using System.Text;

namespace Ini
{
    /// 
    /// Create a New INI file to store or load data
    /// 
    public class IniFile
    {
        public string path;

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section,
            string key,string val,string filePath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section,
                 string key,string def, StringBuilder retVal,
            int size,string filePath);

        /// 
        /// INIFile Constructor.
        /// 
        /// 
        public IniFile(string INIPath)
        {
            path = INIPath;
        }
        /// 
        /// Write Data to the INI File
        /// 
        /// 
        /// Section name
        /// 
        /// Key Name
        /// 
        /// Value Name
        public void IniWriteValue(string Section,string Key,string Value)
        {
            WritePrivateProfileString(Section,Key,Value,this.path);
        }
        
        /// 
        /// Read Data Value From the Ini File
        /// 
        /// 
        /// 
        /// 
        /// 
        public string IniReadValue(string Section,string Key)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(Section,Key,"",temp, 
                                            255, this.path);
            return temp.ToString();

        }
    }
}

INI 파일에 설정을 저장해두자. kernel32.dll을 Import하니 이리도 간단하다 캬~

[출처]CODEPROJECT : An INI file handling class using C#
Posted by lI헐헐Il
,

쿼리분석기의 단축키

 

조금 길긴 하지만.. 알아두면 편한것들은 파란색으로 처리하였습니다.. ^^*

 

작업 바로 가기 키
책갈피: 모든 책갈피 지우기 Ctrl-Shift-F2
책갈피: 책갈피를 삽입하거나 제거(토글) Ctrl+F2
책갈피: 다음 책갈피로 이동 F2
책갈피: 이전 책갈피로 이동 Shift+F2
쿼리 취소 Alt+Break
연결: 연결 Ctrl+O
연결: 연결 끊기 Ctrl+F4
연결: 연결 끊기 및 하위 창 닫기 Ctrl+F4
데이터베이스 개체 정보 Alt+F1
편집: 활성 편집기 창 지우기 Ctrl+Shift+Del
편집: 코드에 주석 달기 Ctrl+Shift+C
편집: 복사. Ctrl+Ins와 같음. Ctrl+C
편집: 잘라내기. Shift+Del과 같음 Ctrl+X
편집: 내어쓰기 Shift+TAB
편집: 편집 창 마지막 줄 삭제 Ctrl+Del
편집: 찾기 Ctrl+F
편집: 해당 줄 번호로 이동 Ctrl+G
편집: 들여쓰기 Tab
편집: 소문자로 변환 Ctrl+Shift+L
편집: 대문자로 변환 Ctrl+Shift+U
편집: 붙여넣기. Shift+Insert와 같음 Ctrl+V
편집: 주석 제거 Ctrl+Shift+R
편집: 최근 검색 재실행 또는 다음 찾기 F3
편집: 바꾸기 Ctrl+H
편집: 모두 선택 Ctrl+A
편집: 실행 취소 Ctrl+Z
쿼리 실행: Ctrl+E와 같음(이전 버전과의 호환성) F5
SQL 쿼리 분석기 도움말 F1
선택한 Transact-SQL 문에 대한 도움말 Shift+F1
탐색: 쿼리와 결과 창 사이 전환 F6
탐색: 창 전환 Shift+F6
탐색: 창 선택기 Ctrl+W
새 쿼리 창 열기 Ctrl+N
개체 브라우저(표시/숨기기) F8
개체 검색 F4
쿼리 구문 분석 및 구문 검사 Ctrl+F5
인쇄 Ctrl+P
결과: 표 형태로 결과 표시 Ctrl+D
결과: 텍스트 형식으로 결과 표시 Ctrl+T
결과: 분할자 이동 Ctrl+B
결과: 파일로 결과 저장 Ctrl+Shift+F
결과: 결과 창 표시(토글) Ctrl+R
저장 Ctrl+S
템플릿: 템플릿 삽입 Ctrl+Shift+Insert
템플릿: 템플릿 매개 변수 바꾸기 Ctrl+Shift+M
튜닝: 예상 실행 계획 표시 Ctrl+L
튜닝: 실행 계획 표시(설정/해제 전환) Ctrl+K
튜닝: 인덱스 튜닝 마법사 Ctrl+I
튜닝: 클라이언트 통계 표시 Ctrl+Shift+S
튜닝: 서버 추적 표시 Ctrl+Shift+T
데이터베이스 사용 Ctrl+U

Posted by lI헐헐Il
,
SELECT * FROM DBO.SYSOBJECTS
WHERE xTYPE = 'U'
AND [NAME] LIKE '%검색어%' -- 테이블명을 LIKE 조건으로 검색
ORDER BY [NAME]


xTYPE의 종류

AF : 집계함수

C : CHECK 제약조건

D : DEFAULT 제약조건 혹은 독립실행형

F : FOREIGN 제약조건

PK : Primay Key 제약조건

P : Stored Procedure

FN : SQL 스칼라함수

S : 시스템 기본 테이블

U : 테이블(사용자정의)

UQ : UNIQUE 제약조건

V : 뷰

 


SELECT * 
FROM INFORMATION_SCHEMA.TABLES  AS TBL
INNER JOIN INFORMATION_SCHEMA.COLUMNS AS CLM ON TBL.TABLE_NAME = CLM.TABLE_NAME 
WHERE COLUMN_NAME LIKE '%검색어%' AND TABLE_TYPE = 'BASE TABLE' 
-- 컬럼명으로 검색하여 테이블 정보 출력

SELECT DISTINCT B.NAME FROM SYSCOLUMNS A, SYSOBJECTS B
WHERE A.ID = B.ID
AND B.XTYPE = 'U' AND A.NAME LIKE '%컬럼명%' -- 해당 컬럼명이 포함된 테이블 이름을 반환

SELECT DISTINCT O.NAME FROM DBO.SYSOBJECTS O
INNER JOIN DBO.SYSCOMMENTS C ON O.ID = C.ID
WHERE O.XTYPE = 'P' AND C.TEXT LIKE '%KEYWORD%'; -- SP 내에서 내용 검색
Posted by lI헐헐Il
,

EvnetLog 쓰기

IT/C# 2013. 3. 5. 10:56
try ~ catch 구문과 함께 Exception 발생 시 이벤트로그를 남길 수 있다.
using System;
using System.Diagnostics;
using System.Threading;

class MySample{

    public static void Main(){

        // Create the source, if it does not already exist. 
        if(!EventLog.SourceExists("MySource"))
        {
             //An event log source should not be created and immediately used. 
             //There is a latency time to enable the source, it should be created 
             //prior to executing the application that uses the source. 
             //Execute this sample a second time to use the new source.
            EventLog.CreateEventSource("MySource", "MyNewLog");
            Console.WriteLine("CreatedEventSource");
            Console.WriteLine("Exiting, execute the application a second time to use the source.");
            // The source is created.  Exit the application to allow it to be registered. 
            return;
        }

        // Create an EventLog instance and assign its source.
        EventLog myLog = new EventLog();
        myLog.Source = "MySource";

        // Write an informational entry to the event log.    
        myLog.WriteEntry("Writing to event log.");

    }
}

[출처] http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx MSDN =^^=
Posted by lI헐헐Il
,