선언할때 줄 잘 맞춰서 코딩해 놨는데 공백이 사라지는 억울함이....

 

도구 -> 옵션 -> 텍스트 편집기 -> C# -> 서식 -> 간격 -> 기타 간격 옵션을 설정합니다. -> 선언문의 공백을 무시합니다.

' 체크 '

 

 

'.Net > C#' 카테고리의 다른 글

[C#] 정적 생성자 (static 멤버 초기화)  (0) 2013.01.15
[C#] Assemble.load  (0) 2013.01.15
[C#] C# as 연산자  (0) 2013.01.09
[C#] StackTrace  (0) 2013.01.08
[C#] DllImportAttribut  멤버  (0) 2013.01.04
posted by 뚱2

링크 : http://www.devpia.com/NET2/EvaCast/Lecture/?fCode=2&sCode=5&c=9 

링크 : http://aspectdotnet.codeplex.com/

링크 : https://www.facultyresourcecenter.com/curriculum/pfv.aspx?ID=8658&c1=en-us&c2=0



자바에서 정말 편하게 사용했던 AspectJ 


닷넷에 와서 비슷하걸 찾고 있는데 내 입맛에 맞는걸 아직 찾지 못했다.


시간을 두고 좀더 찾아봐야 할 것 같다.

'.Net > .Net' 카테고리의 다른 글

[.Net] AOP 프로그래밍  (0) 2013.01.23
[.Net] CodeDomProvider  (0) 2013.01.15
[.Net] 웹 자동화 구현 클래스  (0) 2013.01.09
[.Net] pinvoke.net  (0) 2013.01.07
[.Net] Windows 서비스 응용 프로그램  (0) 2012.12.07
posted by 뚱2

[C#] C# as 연산자

.Net/C# 2013. 1. 9. 14:42

링크 : http://msdn.microsoft.com/ko-kr/library/cscsdfbt(VS.80).aspx 


호환되는 참조 형식 간에 변환을 수행하는 데 사용됩니다. 예를 들면 다음과 같습니다.

string s = someObject as string;
if (s != null)
{
    // someObject is a string.
}

as 연산자는 캐스트 연산과 비슷하지만 변환이 가능하지 않은 경우에 as를 사용하면 예외가 발생하지 않고 대신 null이 반환됩니다. 식의 정확한 형식은 다음과 같습니다.

expression as type

이 식은 아래의 식과 동일합니다.

expression is type ? (type)expression : (type)null

그러나 expression 이 한 번만 계산된다는 점은 다릅니다.

as 연산자는 오직 참조 변환과 boxing 변환만을 수행합니다. as 연산자는 사용자 정의 변환과 같은 다른 변환을 수행할 수 없습니다. 사용자 정의 변환은 이 연산자 대신 캐스트 식을 사용하여 수행해야 합니다.

// cs_keyword_as.cs
// The as operator.
using System;
class Class1
{
}

class Class2
{
}

class MainClass
{
    static void Main()
    {
        object[] objArray = new object[6];
        objArray[0] = new Class1();
        objArray[1] = new Class2();
        objArray[2] = "hello";
        objArray[3] = 123;
        objArray[4] = 123.4;
        objArray[5] = null;

        for (int i = 0; i < objArray.Length; ++i)
        {
            string s = objArray[i] as string;
            Console.Write("{0}:", i);
            if (s != null)
            {
                Console.WriteLine("'" + s + "'");
            }
            else
            {
                Console.WriteLine("not a string");
            }
        }
    }
}

출력

0:not a string
1:not a string
2:'hello'
3:not a string
4:not a string
5:not a string

'.Net > C#' 카테고리의 다른 글

[C#] Assemble.load  (0) 2013.01.15
[Visual Studio 2010] C# 선언할때 공백 제거 문제  (0) 2013.01.14
[C#] StackTrace  (0) 2013.01.08
[C#] DllImportAttribut  멤버  (0) 2013.01.04
[C#] Visual C# 메소드를 비동기로 호출하는 방법  (0) 2012.04.14
posted by 뚱2

.Net에서 WebBrowser 컨트롤을 임포트 해서 해결할수도 있고

 

좀더 아래 로우레벨로 내려가서 해결할수도 있습니다.

 

링크 (WebClient) : http://msdn.microsoft.com/ko-kr/library/system.net.webclient(v=vs.80).aspx

using System;
using System.Net;
using System.IO;

public class Test
{
    public static void Main (string[] args)
    {
        if (args == null || args.Length == 0)
        {
            throw new ApplicationException ("Specify the URI of the resource to retrieve.");
        }
        WebClient client = new WebClient ();

        // Add a user agent header in case the
        // requested URI contains a query.

        client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

        Stream data = client.OpenRead (args[0]);
        StreamReader reader = new StreamReader (data);
        string s = reader.ReadToEnd ();
        Console.WriteLine (s);
        data.Close ();
        reader.Close ();
    }
}

 

이벤트 (DownloadProgressChanged) : http://msdn.microsoft.com/ko-kr/library/system.net.webclient.downloadprogresschanged(v=vs.80).aspx 


링크 (WebRequest) : http://msdn.microsoft.com/ko-kr/library/system.net.webrequest(v=vs.95).aspx 

 

'.Net > .Net' 카테고리의 다른 글

[.Net] CodeDomProvider  (0) 2013.01.15
[.Net] Aspect Oriented Programming With .Net  (0) 2013.01.14
[.Net] pinvoke.net  (0) 2013.01.07
[.Net] Windows 서비스 응용 프로그램  (0) 2012.12.07
[.Net] Zlib Wrapper  (0) 2012.05.22
posted by 뚱2

[C#] StackTrace

.Net/C# 2013. 1. 8. 15:36

아는 동생이 알려주길래 얼른 사용해봄 나중을 위해서 기록...

private void GetDebugInfo()
{
    string szDebugInfo = string.Empty;

    System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(true);

    System.Diagnostics.Debug.Write("*******************************");
    for(int i=1; i<trace.FrameCount; i++)
    {
        if(trace.GetFrame(i).GetFileName() != null)
        {
            if(trace.GetFrame(i).GetFileName() != String.Empty)
                 System.Diagnostics.Debug.Write(trace.GetFrame(i).ToString());
        }
    }
    System.Diagnostics.Debug.Write("*******************************");
}

 

posted by 뚱2

[.Net] pinvoke.net

.Net/.Net 2013. 1. 7. 16:46

링크 : http://www.pinvoke.net/index.aspx 

 

win32 API 를 .Net에서 사용할때 .Net에 맞게 DllImport를 해야 하는데 그 변환 문법이 만만치 않다.

각 함수별로 잘 정리되어 있는 사이트

 

* 사이트 메인 화면을 보면 Visual Studio 2010, 2012 Add-In 프로그램도 존재한다. Winform으로 개발시 유용할듯

'.Net > .Net' 카테고리의 다른 글

[.Net] Aspect Oriented Programming With .Net  (0) 2013.01.14
[.Net] 웹 자동화 구현 클래스  (0) 2013.01.09
[.Net] Windows 서비스 응용 프로그램  (0) 2012.12.07
[.Net] Zlib Wrapper  (0) 2012.05.22
[.Net] Inter-Process Communication  (0) 2012.04.17
posted by 뚱2

[C#] DllImportAttribut  멤버

.Net/C# 2013. 1. 4. 14:03

링크 : http://msdn.microsoft.com/ko-kr/library/system.runtime.interopservices.dllimportattribute_members(v=vs.90).aspx 

참조 : http://blog.naver.com/luvinuns?Redirect=Log&logNo=90051065276


'.Net > C#' 카테고리의 다른 글

[C#] C# as 연산자  (0) 2013.01.09
[C#] StackTrace  (0) 2013.01.08
[C#] Visual C# 메소드를 비동기로 호출하는 방법  (0) 2012.04.14
[C#] Assembly Version Loading  (0) 2012.04.06
[C#] VS 2008 서식 자동 해제  (0) 2012.04.06
posted by 뚱2

링크 : http://dalbong2.net/entry/SpringNET-%EA%B0%9C%EB%B0%9C-%EA%B0%80%EC%9D%B4%EB%93%9C 


문서 작성해 주신분께 감사드립니다.


'.Net > Spring.Net' 카테고리의 다른 글

[Spring.Net] Spring.NET_guide_ensoa_v.0.2.pdf  (0) 2012.03.16
posted by 뚱2

링크 : http://msdn.microsoft.com/ko-kr/library/y817hyb6(v=vs.80).aspx 


연습: http://msdn.microsoft.com/ko-kr/library/zt39148a(v=vs.80).aspx 


UAC : http://www.codeproject.com/Articles/35773/Subverting-Vista-UAC-in-Both-32-and-64-bit-Archite 

'.Net > .Net' 카테고리의 다른 글

[.Net] 웹 자동화 구현 클래스  (0) 2013.01.09
[.Net] pinvoke.net  (0) 2013.01.07
[.Net] Zlib Wrapper  (0) 2012.05.22
[.Net] Inter-Process Communication  (0) 2012.04.17
[.Net] IPC  (0) 2012.04.16
posted by 뚱2

[.Net] Zlib Wrapper

.Net/.Net 2012. 5. 22. 11:08

링크 : http://www.componentace.com/zlib_.NET.htm 

링크 : http://zlibnetwrapper.sourceforge.net/ 

'.Net > .Net' 카테고리의 다른 글

[.Net] pinvoke.net  (0) 2013.01.07
[.Net] Windows 서비스 응용 프로그램  (0) 2012.12.07
[.Net] Inter-Process Communication  (0) 2012.04.17
[.Net] IPC  (0) 2012.04.16
[.Net] 관리코드에서 메모리 누수 및 방지  (0) 2012.04.11
posted by 뚱2

[.Net] Inter-Process Communication

.Net/.Net 2012. 4. 17. 20:00

1. Ipc클래스 이용

링크 : http://anoriginalidea.wordpress.com/2007/08/09/simple-inter-process-communication-in-vbnet/


2. 표준 입출력 이용

링크 : http://vervain.tistory.com/75#comment5317331 

'.Net > .Net' 카테고리의 다른 글

[.Net] Windows 서비스 응용 프로그램  (0) 2012.12.07
[.Net] Zlib Wrapper  (0) 2012.05.22
[.Net] IPC  (0) 2012.04.16
[.Net] 관리코드에서 메모리 누수 및 방지  (0) 2012.04.11
[.Net] 가비지 수집 모니터링  (0) 2012.04.11
posted by 뚱2

[.Net] IPC

.Net/.Net 2012. 4. 16. 14:24

링크 : http://msdn.microsoft.com/ko-kr/library/system.runtime.remoting.channels.ipc(v=vs.90).aspx

posted by 뚱2

링크 : http://support.microsoft.com/kb/315582 


비동기로 UI 호출 하기 : http://jongkok4.net/entry/%C6%DFc-UI-%BE%B2%B7%B9%B5%E5-%B8%B6%BC%A3%B8%B5-Invoke-BeginInvoke?TSSESSIONjongkok4net=6e5ec00b34c31e0126e9a64412f7a627


'.Net > C#' 카테고리의 다른 글

[C#] StackTrace  (0) 2013.01.08
[C#] DllImportAttribut  멤버  (0) 2013.01.04
[C#] Assembly Version Loading  (0) 2012.04.06
[C#] VS 2008 서식 자동 해제  (0) 2012.04.06
[C#] log4net  (0) 2012.04.03
posted by 뚱2

[XtraGrid] Online Document

.Net/XtraGrid 2012. 4. 13. 17:04

링크 : http://documentation.devexpress.com/#WindowsForms/clsDevExpressXtraGridViewsGridGridViewtopic

'.Net > XtraGrid' 카테고리의 다른 글

[XtraGrid] XtraGrid Option  (0) 2013.01.24
[XtraGrid] Copy & Paste 구현  (0) 2012.04.11
[XtraGrid] How to make my grid columns read-only  (0) 2012.04.08
[XtraGrid] Checkbox 구현하기  (1) 2012.04.06
[XtraGrid] Fixed Columns  (0) 2012.04.05
posted by 뚱2

[XtraGrid] Copy & Paste 구현

.Net/XtraGrid 2012. 4. 11. 14:06

링크 : http://www.devexpress.com/Support/Center/p/A1266.aspx 

Copy 구현 : http://www.devexpress.com/Support/Center/p/A332.aspx

셀렉션 옵션 : http://documentation.devexpress.com/#WindowsForms/CustomDocument711  



using System;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Data;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;

using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.Utils.Drawing;


namespace KIS.DevExpressHelper
{
    public class GridLClipboardHelper
    {
        private const string CellDelimiter = "\t";
        private const string LineDelimiter = "\r\n";
        protected GridView _view;

        /// 생성자
        public GridLClipboardHelper(GridView view)
        {
            this.View = view;
        }
        public GridView View
        {
            get { return _view; }
            set
            {
                if ( _view != value )
                {
                    Detach();
                    Attach(value);
                }
            }
        }

        protected virtual void Attach(GridView view)
        {
            if ( view == null )
                return;
            this._view = view;

            if ( view.IsMultiSelect == false )
            {
                view.OptionsSelection.MultiSelect       = true;
                view.OptionsSelection.MultiSelectMode   = GridMultiSelectMode.RowSelect;
            }

            this.View.KeyDown       += new KeyEventHandler(View_KeyDown);
        }

        private bool CompareGrid(GridView srcView, GridView tgtView)
        {
            int srcCnt = srcView.Columns.Count;
            int tgtCnt = tgtView.Columns.Count;

            if ( srcView == null || tgtView == null )
            {
                return false;
            }

            if ( srcCnt != tgtCnt )
            {
                return false;
            }

            for ( int i = 0; i < srcCnt; i++ )
            {
                if ( srcView.Columns[i].ColumnType != tgtView.Columns[i].ColumnType 
                     || srcView.Columns[i].FieldName != tgtView.Columns[i].FieldName
                    )
                {
                    return false;
                }
            }

            return true;
        }

        void View_KeyDown(object sender, KeyEventArgs e)
        {
            GridView view = sender as GridView;

            // 붙여 넣기
            if ( this.CompareGrid(this._view, view) == true && view.IsMultiSelect == true && e.Control == true && e.KeyCode == Keys.V )
            {
                this.Paste(view);
            }
            // 복사하기
            else if ( this.CompareGrid(this._view, view) == true && view.IsMultiSelect == true && e.Control == true && e.KeyCode == Keys.C )
            {
                e.SuppressKeyPress = true;
                this.Copy(view);
            }
            // 모두 선택
            else if ( this.CompareGrid(this._view, view) == true && view.IsMultiSelect == true && e.Control == true && e.KeyCode == Keys.A )
            {
                this.SelectAll(view);
            }
            // 삭제
            else if ( this.CompareGrid(this._view, view) == true && view.IsMultiSelect == true &&  e.KeyCode == Keys.Delete )
            {
                this.DeleteRows(view);
            }
            // 오려내기
            else if ( this.CompareGrid(this._view, view) == true && view.IsMultiSelect == true && e.Control == true && e.KeyCode == Keys.X )
            {
                this.Copy(view);
                this.DeleteRows(view);
            }
        }

        /// 모두 선택
        public void SelectAll(GridView view)
        {
            view.SelectAll();
        }

        // 복사하기
        public void Copy(GridView view)
        {
            StringBuilder sb = new StringBuilder();
            int columnNameCnt = view.Columns.Count;
            for ( int i = 0; i < columnNameCnt; i++ )
            {
                try
                {
                    sb.Append(view.Columns[i].FieldName.ToString());
                }
                catch ( ArgumentException )
                {
                    sb.Append("");
                }

                if ( i+1 < columnNameCnt )
                    sb.Append(CellDelimiter);
            }
            sb.Append(LineDelimiter);


            int[] rows = view.GetSelectedRows();
            int rowsCnt = rows.Length;
            for ( int i = 0; i < rowsCnt; i++ )
            {
                int handle = rows[i];
                DataRowView rowView = view.GetRow(handle) as DataRowView;
                if ( rowView != null )
                {
                    for ( int j = 0; j < columnNameCnt; j++ )
                    {
                        try
                        {
                            sb.Append(rowView[view.Columns[j].FieldName].ToString());
                        }
                        catch ( ArgumentException )
                        {
                            sb.Append("");
                        }

                        if ( j+1 < columnNameCnt )
                            sb.Append(CellDelimiter);
                    }
                }
                if ( i+1 < rowsCnt )
                    sb.Append(LineDelimiter);
            }

            DataObject data = new DataObject();
            data.SetData(DataFormats.Text, sb.ToString());
            Clipboard.Clear();
            Clipboard.SetDataObject(data, true);
        }

        // 붙여넣기
        public void Paste(GridView view)
        {
            IDataObject data = Clipboard.GetDataObject();
            if ( data.GetDataPresent(DataFormats.Text) == true )
            {
                view.BeginUpdate();
                try
                {
                    string strData          = data.GetData(DataFormats.Text) as string;
                    string[] strRows        = strData.Split(new string[] { LineDelimiter }, StringSplitOptions.None);
                    string[] strColumnNames = strRows[0].Split(new string[] { CellDelimiter }, StringSplitOptions.None);

                    List< object > list = new List< object >();
                    int dataCount               = strRows.Length-1; // 헤더 개수 제외
                    int rowHandle               = view.FocusedRowHandle;
                    int targetDeleteRowCount    = view.DataRowCount - rowHandle + 1;

                    if ( rowHandle != GridControl.InvalidRowHandle && rowHandle != GridControl.NewItemRowHandle )
                    {
                        // 붙여 넣기할 Row가 현재 선택된 행부터 밑에 행보다 많다.
                        if ( targetDeleteRowCount > dataCount )
                        {
                            for ( int i = rowHandle + dataCount; i < view.DataRowCount; i++ )
                            {
                                list.Add(view.GetRow(i));
                            }
                        }

                        // 현재 선택된 행부터 끝까지 삭제한다.
                        for ( int i = view.DataRowCount-1; i >= rowHandle; i-- )
                        {
                            view.DeleteRow(i);
                        }
                    }
                    else if ( rowHandle == GridControl.NewItemRowHandle )
                    {
                        view.DeleteRow(rowHandle);
                    }

                    for ( int i = 1; i < strRows.Length; i++ )
                    {
                        view.AddNewRow();
                        int handle = view.FocusedRowHandle;

                        string[] strCells = strRows[i].Split(new string[] { CellDelimiter }, StringSplitOptions.None);
                        int colCnt = strColumnNames.Length;
                        for ( int j = 0; j < colCnt; j++ )
                        {
                            if ( strColumnNames[j].Trim().Equals("") == false && j < strCells.Length )
                            {
                                try
                                {
                                    Type t = view.Columns[j].ColumnType;
                                    object value = null;
                                    if ( t == typeof(int) )
                                    {
                                        if ( strCells[j] != null && strCells[j].ToString().Equals("") == false )
                                        {
                                            try
                                            {
                                                value = Convert.ToInt32(strCells[j]);
                                                if ( value != null )
                                                    view.SetRowCellValue(handle, strColumnNames[j], value);
                                            }
                                            catch ( Exception ex )
                                            {
                                                System.Console.WriteLine(ex.StackTrace);
                                            }
                                        }
                                    }
                                    else if ( t == typeof(DateTime) )
                                    {
                                        if ( strCells[j] != null && strCells[j].ToString().Equals("") == false )
                                        {
                                            try
                                            {
                                                value = Convert.ToDateTime(strCells[j]);
                                                if ( value != null )
                                                    view.SetRowCellValue(handle, strColumnNames[j], value);
                                            }
                                            catch ( Exception ex )
                                            {
                                                System.Console.WriteLine(ex.StackTrace);
                                            }
                                        }
                                    }
                                    else if ( t == typeof(string) )
                                    {
                                        if ( strCells[j] != null )
                                        {
                                            try
                                            {
                                                value = Convert.ToString(strCells[j]);
                                                if ( value != null )
                                                    view.SetRowCellValue(handle, strColumnNames[j], value);
                                            }
                                            catch ( Exception ex )
                                            {
                                                System.Console.WriteLine(ex.StackTrace);
                                            }
                                        }
                                    }
                                }
                                catch ( Exception ex)
                                {
                                    //MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace);
                                }
                            }//if ( strColumnNames[j].Trim().Equals("") == false )
                        }//for ( int j = 0; j < colCnt; j++ )
                    }//for ( int i = 1; i < strRows.Length; i++ )

                    DataView dv = view.DataSource as DataView;
                    for ( int i = 0; i < list.Count; i++ )
                    {
                        DataRowView drv = list[i] as DataRowView;
                        if ( drv != null )
                        {
                            DataRowView newDRV = dv.AddNew();
                            newDRV.BeginEdit();
                            try
                            {
                                int columNameCount= drv.Row.Table.Columns.Count;
                                for ( int j = 0; j < columNameCount; j++ )
                                {
                                    string fieldName = drv.Row.Table.Columns[j].ColumnName;
                                    newDRV[fieldName] = drv[fieldName];
                                }
                                newDRV.EndEdit();
                            }
                            catch ( Exception )
                            {
                                newDRV.CancelEdit();
                            }
                        }
                    }
                }
                catch ( Exception ex )
                {
                    MessageBox.Show(ex.StackTrace);
                }
                finally
                {
                    view.EndUpdate();
                }
            }//if ( data.GetDataPresent(DataFormats.Text) == true )
        }


        /// 현재 선택된 로우를 삭제한다.
        private void DeleteRows(GridView view)
        {
            view.BeginUpdate();
            int[] rows = view.GetSelectedRows();
            for ( int i = rows.Length-1; i >= 0 ; i-- )
            {
                view.DeleteRow(rows[i]);
            }
            view.EndUpdate();
        }

        protected virtual void Detach()
        {
            if ( this._view == null )
                return;

            this.View.KeyDown       -= new KeyEventHandler(View_KeyDown);
            _view = null;
        }
    }
}

'.Net > XtraGrid' 카테고리의 다른 글

[XtraGrid] XtraGrid Option  (0) 2013.01.24
[XtraGrid] Online Document  (0) 2012.04.13
[XtraGrid] How to make my grid columns read-only  (0) 2012.04.08
[XtraGrid] Checkbox 구현하기  (1) 2012.04.06
[XtraGrid] Fixed Columns  (0) 2012.04.05
posted by 뚱2

링크 : http://msdn.microsoft.com/ko-kr/magazine/cc163491.aspx 


메모리 릭 찾기

Windbg : http://www.codeproject.com/Articles/31382/Memory-Leak-Detection-Using-Windbg 

NET : http://www.codeproject.com/Articles/19490/Memory-Leak-Detection-in-NET


posted by 뚱2

CLR Profiler : http://www.microsoft.com/download/en/details.aspx?id=13382 

http://www.microsoft.com/downloads/ko-kr/details.aspx?familyid=fd02c7d6-5306-41f2-a1be-b7dcb74c9c0b 







* PerfMon.exe 

    위치 : C:\Windows\System32\PerfMon.exe




posted by 뚱2

링크 : http://msdn.microsoft.com/ko-kr/magazine/cc163528.aspx 


프로세스의 메모리 사용 조사 : http://msdn.microsoft.com/ko-kr/library/cc438089(v=vs.71).aspx

posted by 뚱2

링크 : http://msdn.microsoft.com/ko-kr/library/dd465122.aspx 

링크 : http://msdn.microsoft.com/ko-kr/library/018hxwa8.aspx


이렇게도 사용할수 있군요. 간단한 메소드는 델리게이트 선언하지 않고 바로 사용 할 수 있을듯합니다.


응용 : http://www.devpia.co.kr/MAEUL/Contents/Detail.aspx?BoardID=18&MAEULNO=8&no=1723&page=11 


범용 적으로 사용 하게 만든 클래스 사실 제네릭 인자 3개 더 추가밖에 없습니다.


    
public static class ControlExt
    {
        public static void InvokeIfNeeded(this Control control, Action action)
        {
            if ( control.InvokeRequired )
            {
                control.Invoke(action);
            }
            else
            {
                action();
            }
        }

        public static void InvokeIfNeeded< T >(this Control control, Action< T > action, T arg)
        {
            if ( control.InvokeRequired )
            {
                control.Invoke(action, arg);
            }
            else
            {
                action(arg);
            }
        }

        public static void InvokeIfNeeded< T1 , T2 >(this Control control, Action< T1 , T2 > action, T1 arg1, T2 arg2)
        {
            if ( control.InvokeRequired )
            {
                control.Invoke(action, new object[] {arg1, arg2});
            }
            else
            {
                action(arg1, arg2);
            }
        }

        public static void InvokeIfNeeded< T1, T2, T3 >(this Control control, Action< T1, T2, T3 > action, T1 arg1, T2 arg2, T3 arg3)
        {
            if ( control.InvokeRequired )
            {
                control.Invoke(action, new object[] { arg1, arg2, arg3 });
            }
            else
            {
                action(arg1, arg2, arg3);
            }
        }

        public static void InvokeIfNeeded< T1, T2, T3, T4 >(this Control control, Action< T1, T2, T3, T4 > action, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
        {
            if ( control.InvokeRequired )
            {
                control.Invoke(action, new object[] { arg1, arg2, arg3, arg4 });
            }
            else
            {
                action(arg1, arg2, arg3, arg4);
            }
        }
    }

posted by 뚱2

'.Net > XtraGrid' 카테고리의 다른 글

[XtraGrid] Online Document  (0) 2012.04.13
[XtraGrid] Copy & Paste 구현  (0) 2012.04.11
[XtraGrid] Checkbox 구현하기  (1) 2012.04.06
[XtraGrid] Fixed Columns  (0) 2012.04.05
[XtraGrid] DevExpress XtraGrid  (0) 2012.03.28
posted by 뚱2

[C#] Assembly Version Loading

.Net/C# 2012. 4. 6. 19:35

현재 어셈블리 버전을 읽는 방법 이다.




// AssemblyInfo.cs
// 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 버전이 자동으로
// 지정되도록 할 수 있습니다.
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.5.*")]
[assembly: AssemblyFileVersion("0.5.*")]

// Test.cs
// 현재 실행 프로그램의 어셈플리를 로딩한다.
string msg = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
MessageBox.Show("Version=" + msg);

참고로 버전은 Major.Minor.Build.Revision 입니다.

'.Net > C#' 카테고리의 다른 글

[C#] DllImportAttribut  멤버  (0) 2013.01.04
[C#] Visual C# 메소드를 비동기로 호출하는 방법  (0) 2012.04.14
[C#] VS 2008 서식 자동 해제  (0) 2012.04.06
[C#] log4net  (0) 2012.04.03
[C#] vshosting.exe 가 뭘까요?  (0) 2012.03.26
posted by 뚱2
사이트에 있는 예제를 약간 수정했다.
엑셀과 비슷하게 Shift + 클릭으로 범위를 클릭할수 있게 변경했다.
 
    public class GridCheckMarksMultiSelectionHelper
    {
        private readonly string             markFieldName = "CheckMarkSelection";
        protected GridView                  _view;
        protected ArrayList                 selection;
        protected GridColumn                column;
        protected RepositoryItemCheckEdit   edit;
        protected const int                 CheckboxIndent = 4;

        /// 
        /// 생성자
        /// 
        public GridCheckMarksMultiSelectionHelper()
        {
            selection = new ArrayList();
        }
        public GridCheckMarksMultiSelectionHelper(GridView view)
            : this()
        {
            this.View = view;
        }
        public GridView View
        {
            get { return _view; }
            set
            {
                if (_view != value)
                {
                    Detach();
                    Attach(value);
                }
            }
        }
        public string MarkFieldName
        {
            get
            {
                return this.markFieldName;
            }
        }

        private bool isMultiSelect = false;
        public bool IsMultiSelect
        {
            get
            {
                return this.isMultiSelect;
            }

            private set
            {
                this.isMultiSelect = value;
            }
        }


        public GridColumn CheckMarkColumn { get { return column; } }
        public int SelectedCount { get { return selection.Count; } }
        public object GetSelectedRow(int index)
        {
            return selection[index];
        }
        public int GetSelectedIndex(object row)
        {
            foreach (object record in selection)
                if ((record as DataRowView).Row == (row as DataRowView).Row)
                    return selection.IndexOf(record);
            return selection.IndexOf(row);
        }
        public void ClearSelection(GridView view)
        {
            selection.Clear();
            Invalidate(view);
        }
        public void SelectAll(GridView view)
        {
            selection.Clear();
            // fast (won't work if the grid is filtered)
            //if(_view.DataSource is ICollection)
            //	selection.AddRange(((ICollection)_view.DataSource));
            //else
            // slow:
            for (int i = 0; i < view.DataRowCount; i++)
                selection.Add(view.GetRow(i));
            Invalidate(view);
        }
        public void SelectGroup(int rowHandle, bool select, GridView view)
        {
            if (IsGroupRowSelected(rowHandle, view) && select) return;
            for (int i = 0; i < view.GetChildRowCount(rowHandle); i++)
            {
                int childRowHandle = view.GetChildRowHandle(rowHandle, i);
                if (view.IsGroupRow(childRowHandle))
                    SelectGroup(childRowHandle, select, view);
                else
                    SelectRow(childRowHandle, select, false, view);
            }
            Invalidate(view);
        }
        void SelectRow(int rowHandle, bool select, bool invalidate, GridView view)
        {
            if (IsRowSelected(rowHandle, view) == select) return;
            object row = view.GetRow(rowHandle);
            if (select)
                selection.Add(row);
            else
                selection.Remove(row);
            if (invalidate)
            {
                Invalidate(view);
            }
        }
        void SelectRow(object row, bool select, bool invalidate, GridView view)
        {
            if (IsRowSelected(row, view) == select) return;
            if (select)
                selection.Add(row);
            else
                selection.Remove(row);
            if (invalidate)
            {
                Invalidate(view);
            }
        }
        public void SelectRow(int rowHandle, bool select, GridView view)
        {
            SelectRow(rowHandle, select, true, view);
        }
        public void SelectRow(object row, bool select, GridView view)
        {
            SelectRow(row, select, true, view);
        }
        public void InvertRowSelection(int rowHandle, GridView view)
        {
            if (view.IsDataRow(rowHandle))
            {
                SelectRow(rowHandle, !IsRowSelected(rowHandle, view), view);
            }
            if (view.IsGroupRow(rowHandle))
            {
                SelectGroup(rowHandle, !IsGroupRowSelected(rowHandle, view), view);
            }
        }
        public bool IsGroupRowSelected(int rowHandle, GridView view)
        {
            for (int i = 0; i < view.GetChildRowCount(rowHandle); i++)
            {
                int row = _view.GetChildRowHandle(rowHandle, i);
                if (view.IsGroupRow(row))
                {
                    if (!IsGroupRowSelected(row, view)) return false;
                }
                else
                    if (!IsRowSelected(row, view)) return false;
            }
            return true;
        }
        public bool IsRowSelected(int rowHandle, GridView view)
        {
            if (view.IsGroupRow(rowHandle))
                return IsGroupRowSelected(rowHandle, view);

            object row = view.GetRow(rowHandle);

            return GetSelectedIndex(row) != -1;
        }
        public bool IsRowSelected(object row, GridView view)
        {
            return GetSelectedIndex(row) != -1;
        }
        protected virtual void Attach(GridView view)
        {
            if (view == null) return;
            selection.Clear();
            this._view = view;
            edit = view.GridControl.RepositoryItems.Add("CheckEdit") as RepositoryItemCheckEdit;
            column = view.Columns.Add();
            column.OptionsColumn.AllowSort = DevExpress.Utils.DefaultBoolean.False;
            column.Visible = true;
            column.VisibleIndex = 0;
            column.FieldName = this.MarkFieldName;
            column.Caption = "Mark";
            column.OptionsColumn.ShowCaption = false;
            column.OptionsColumn.AllowEdit = false;
            column.OptionsColumn.AllowSize = false;
            column.UnboundType = DevExpress.Data.UnboundColumnType.Boolean;
            column.Width = GetCheckBoxWidth();
            // 2012-04-05 ADDED BY KDJ
            column.Fixed = FixedStyle.Left;
            column.ColumnEdit = edit;

            view.Click                      += new EventHandler(View_Click);
            view.CustomDrawColumnHeader     += new ColumnHeaderCustomDrawEventHandler(View_CustomDrawColumnHeader);
            view.CustomDrawGroupRow         += new RowObjectCustomDrawEventHandler(View_CustomDrawGroupRow);
            view.CustomUnboundColumnData    += new CustomColumnDataEventHandler(view_CustomUnboundColumnData);
            view.KeyDown                    += new KeyEventHandler(view_KeyDown);
            view.RowStyle                   += new RowStyleEventHandler(view_RowStyle);

            // 2012-04-05 ADDED BY KDJ
            view.KeyUp                      += new KeyEventHandler(view_KeyUp);
            view.FocusedRowChanged          += new FocusedRowChangedEventHandler(view_FocusedRowChanged);
        }

        void view_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            this._view.BeginUpdate();
            
            // 클릭시 현재 Row 선택되게 하는 루틴
            //bool isSelection = this.IsRowSelected(row, view);
            //this.SelectRow(row, !isSelection, false, view);

            if (this.IsMultiSelect == true)
            {
                int start = 0, end = 0;

                if (e.PrevFocusedRowHandle <= e.FocusedRowHandle)
                {
                    start = e.PrevFocusedRowHandle;
                    end = e.FocusedRowHandle;
                }
                else
                {
                    start = e.FocusedRowHandle;
                    end = e.PrevFocusedRowHandle;
                }

                for (int i = start; i <= end; i++)
                {
                    this.SelectRow(i, true, false, this._view);
                }
                
            }

            this._view.EndUpdate();
        }

        public virtual void DetailViewAttach(GridView view)
        {
            if (view == null) return;
            this._view = view;
            _view.BeginUpdate();
            try
            {
                column = view.Columns[this.MarkFieldName];
                if (column == null)
                {
                    selection.Clear();
                    edit = view.GridControl.RepositoryItems.Add("CheckEdit") as RepositoryItemCheckEdit;
                    column = view.Columns.Add();
                    column.OptionsColumn.AllowSort = DevExpress.Utils.DefaultBoolean.False;
                    column.Visible = true;
                    column.VisibleIndex = 0;
                    column.FieldName = this.MarkFieldName;
                    column.Caption = "Mark";
                    column.OptionsColumn.ShowCaption = false;
                    column.OptionsColumn.AllowEdit = false;
                    column.OptionsColumn.AllowSize = false;
                    column.UnboundType = DevExpress.Data.UnboundColumnType.Boolean;
                    column.Width = GetCheckBoxWidth();
                    column.ColumnEdit = edit;
                }
                edit = view.Columns[this.MarkFieldName].ColumnEdit as RepositoryItemCheckEdit;//view.GridControl.RepositoryItems.Add("CheckEdit") as RepositoryItemCheckEdit;
                view.Click                      += new EventHandler(View_Click);
                view.CustomDrawColumnHeader     += new ColumnHeaderCustomDrawEventHandler(View_CustomDrawColumnHeader);
                view.CustomDrawGroupRow         += new RowObjectCustomDrawEventHandler(View_CustomDrawGroupRow);
                view.CustomUnboundColumnData    += new CustomColumnDataEventHandler(view_CustomUnboundColumnData);
                view.KeyDown                    += new KeyEventHandler(view_KeyDown);
                view.RowStyle                   += new RowStyleEventHandler(view_RowStyle);

                // 2012-04-05 ADDED BY KDJ
                view.KeyUp                      += new KeyEventHandler(view_KeyUp);
                view.FocusedRowChanged          += new FocusedRowChangedEventHandler(view_FocusedRowChanged);
            }
            finally
            {
                _view.EndUpdate();
            }
        }
        protected virtual void Detach()
        {
            if (_view == null) return;
            if (column != null)
                column.Dispose();
            if (edit != null)
            {
                _view.GridControl.RepositoryItems.Remove(edit);
                edit.Dispose();
            }

            _view.Click                     -= new EventHandler(View_Click);
            _view.CustomDrawColumnHeader    -= new ColumnHeaderCustomDrawEventHandler(View_CustomDrawColumnHeader);
            _view.CustomDrawGroupRow        -= new RowObjectCustomDrawEventHandler(View_CustomDrawGroupRow);
            _view.CustomUnboundColumnData   -= new CustomColumnDataEventHandler(view_CustomUnboundColumnData);
            _view.KeyDown                   -= new KeyEventHandler(view_KeyDown);
            _view.RowStyle                  -= new RowStyleEventHandler(view_RowStyle);

            // 2012-04-05 ADDED BY KDJ
            _view.KeyUp                     -= new KeyEventHandler(view_KeyUp);
            _view.FocusedRowChanged         -= new FocusedRowChangedEventHandler(view_FocusedRowChanged);

            _view = null;
        }
        public virtual void DetailViewDetach()
        {
            if (_view == null) return;

            _view.Click                     -= new EventHandler(View_Click);
            _view.CustomDrawColumnHeader    -= new ColumnHeaderCustomDrawEventHandler(View_CustomDrawColumnHeader);
            _view.CustomDrawGroupRow        -= new RowObjectCustomDrawEventHandler(View_CustomDrawGroupRow);
            _view.CustomUnboundColumnData   -= new CustomColumnDataEventHandler(view_CustomUnboundColumnData);
            _view.KeyDown                   -= new KeyEventHandler(view_KeyDown);
            _view.RowStyle                  -= new RowStyleEventHandler(view_RowStyle);

            // 2012-04-05 ADDED BY KDJ
            _view.KeyUp                     -= new KeyEventHandler(view_KeyUp);
            _view.FocusedRowChanged         -= new FocusedRowChangedEventHandler(view_FocusedRowChanged);

            _view = null;
        }
        protected int GetCheckBoxWidth()
        {
            DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo info = edit.CreateViewInfo() as DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo;
            int width = 0;
            GraphicsInfo.Default.AddGraphics(null);
            try
            {
                width = info.CalcBestFit(GraphicsInfo.Default.Graphics).Width;
            }
            finally
            {
                GraphicsInfo.Default.ReleaseGraphics();
            }
            return width + CheckboxIndent * 2;
        }
        protected void DrawCheckBox(Graphics g, Rectangle r, bool Checked)
        {
            DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo info;
            DevExpress.XtraEditors.Drawing.CheckEditPainter painter;
            DevExpress.XtraEditors.Drawing.ControlGraphicsInfoArgs args;
            info = edit.CreateViewInfo() as DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo;
            painter = edit.CreatePainter() as DevExpress.XtraEditors.Drawing.CheckEditPainter;
            info.EditValue = Checked;
            info.Bounds = r;
            info.CalcViewInfo(g);
            args = new DevExpress.XtraEditors.Drawing.ControlGraphicsInfoArgs(info, new DevExpress.Utils.Drawing.GraphicsCache(g), r);
            painter.Draw(args);
            args.Cache.Dispose();
        }
        void Invalidate(GridView view)
        {
            view.CloseEditor();
            view.BeginUpdate();
            view.EndUpdate();
        }
        void view_CustomUnboundColumnData(object sender, CustomColumnDataEventArgs e)
        {
            GridView view = sender as GridView;
            if (e.Column.Caption == "Mark")
            {
                if (e.IsGetData)
                    e.Value = /*IsRowSelected((view.DataSource as IList)[e.ListSourceRowIndex],view);*/  IsRowSelected(view.GetRowHandle(e.ListSourceRowIndex), view);
                else
                    SelectRow((view.DataSource as IList)[e.ListSourceRowIndex], (bool)e.Value, view);
            }
        }
        void view_KeyDown(object sender, KeyEventArgs e)
        {
            GridView view = sender as GridView;

            if (e.KeyCode == Keys.ShiftKey && this.isMultiSelect == false)
            {
                this.IsMultiSelect = true;
            }

            if (view.FocusedColumn.Caption != "Mark" || e.KeyCode != Keys.Space) return;
            InvertRowSelection(view.FocusedRowHandle, view);
        }

        void view_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.ShiftKey & this.isMultiSelect == true)
            {
                this.isMultiSelect = false;
            }
        }

        void View_Click(object sender, EventArgs e)
        {
            GridView view = sender as GridView;
            GridHitInfo info;
            Point pt = view.GridControl.PointToClient(Control.MousePosition);
            Point viewOffset = view.GetViewInfo().Bounds.Location;
            //pt.Offset(-viewOffset.X, -viewOffset.Y);
            info = view.CalcHitInfo(pt);
            if (info.Column != null && info.Column.Caption == "Mark")
            {
                if (info.InColumn)
                {
                    if (SelectedCount == view.DataRowCount)
                        ClearSelection(view);
                    else
                        SelectAll(view);
                }
                if (info.InRowCell)
                {
                    InvertRowSelection(info.RowHandle, view);
                }
            }
            if (info.InRow && view.IsGroupRow(info.RowHandle) && info.HitTest != GridHitTest.RowGroupButton)
            {
                InvertRowSelection(info.RowHandle, view);
            }
        }
        void View_CustomDrawColumnHeader(object sender, ColumnHeaderCustomDrawEventArgs e)
        {

            if (e.Column != null && e.Column.Caption == "Mark")
            {
                GridView view = sender as GridView;
                e.Info.InnerElements.Clear();
                e.Painter.DrawObject(e.Info);
                DrawCheckBox(e.Graphics, e.Bounds, SelectedCount == view.DataRowCount);
                e.Handled = true;
            }
        }
        void View_CustomDrawGroupRow(object sender, RowObjectCustomDrawEventArgs e)
        {
            GridView view = sender as GridView;
            DevExpress.XtraGrid.Views.Grid.ViewInfo.GridGroupRowInfo info;
            info = e.Info as DevExpress.XtraGrid.Views.Grid.ViewInfo.GridGroupRowInfo;

            info.GroupText = "         " + info.GroupText.TrimStart();
            e.Info.Paint.FillRectangle(e.Graphics, e.Appearance.GetBackBrush(e.Cache), e.Bounds);
            e.Painter.DrawObject(e.Info);

            Rectangle r = info.ButtonBounds;
            r.Offset(r.Width + CheckboxIndent * 2 - 1, 0);
            DrawCheckBox(e.Graphics, r, IsGroupRowSelected(e.RowHandle, view));
            e.Handled = true;
        }
        void view_RowStyle(object sender, RowStyleEventArgs e)
        {
            GridView view = sender as GridView;
            if (IsRowSelected(e.RowHandle, view))
            {
                e.Appearance.BackColor = SystemColors.Highlight;
                e.Appearance.ForeColor = SystemColors.HighlightText;
            }
        }
    }


'.Net > XtraGrid' 카테고리의 다른 글

[XtraGrid] Online Document  (0) 2012.04.13
[XtraGrid] Copy & Paste 구현  (0) 2012.04.11
[XtraGrid] How to make my grid columns read-only  (0) 2012.04.08
[XtraGrid] Fixed Columns  (0) 2012.04.05
[XtraGrid] DevExpress XtraGrid  (0) 2012.03.28
posted by 뚱2

[C#] VS 2008 서식 자동 해제

.Net/C# 2012. 4. 6. 10:09

줄 맞춰서 코딩 열심히 하고 Copy & Paste하면은 서식이 자동으로 다시 만들어 진다. ㅡㅡ;

나에게는 참 불편한 기능중에 하나

해제 방법은

'도구 -> 옵션 -> 텍스트 편집기 -> C# -> 서식 -> 일반' 으로 들어가서

모든 서식을 체크 해제한다.



추가 : 이렇게 하니 복사 붙여넣기 할때마다 인던트를 조절해야 하는 불편함이 생긴다.

그럴때는 체크 해주고


선언문의 공백을 무시합니다. 를 체크해준다.



그리고 서식 -> 간격 -> 연산자의 간격을 설정 합니다. -> 이항 연산자 주위의 공백을 무시합니다. 선택

'.Net > C#' 카테고리의 다른 글

[C#] Visual C# 메소드를 비동기로 호출하는 방법  (0) 2012.04.14
[C#] Assembly Version Loading  (0) 2012.04.06
[C#] log4net  (0) 2012.04.03
[C#] vshosting.exe 가 뭘까요?  (0) 2012.03.26
[C#] Dynamic Method Call With Out Parameter  (0) 2012.03.22
posted by 뚱2

[XtraGrid] Fixed Columns

.Net/XtraGrid 2012. 4. 5. 13:22

'.Net > XtraGrid' 카테고리의 다른 글

[XtraGrid] Online Document  (0) 2012.04.13
[XtraGrid] Copy & Paste 구현  (0) 2012.04.11
[XtraGrid] How to make my grid columns read-only  (0) 2012.04.08
[XtraGrid] Checkbox 구현하기  (1) 2012.04.06
[XtraGrid] DevExpress XtraGrid  (0) 2012.03.28
posted by 뚱2

[C#] log4net

.Net/C# 2012. 4. 3. 14:24
링크 :  http://logging.apache.org/log4net/index.html

링크 : http://blog.suromind.com/90 

레퍼런스 : http://logging.apache.org/log4net/release/sdk/index.html

참고 : http://www.venomi.pe.kr/3191513

프로젝트에서 로그를 사용해야 하는데 log4j와 같이 유용하게 사용할수 있을 것 같다.

아래는 내가 사용하는 환경설정이다.




  
    


'.Net > C#' 카테고리의 다른 글

[C#] Assembly Version Loading  (0) 2012.04.06
[C#] VS 2008 서식 자동 해제  (0) 2012.04.06
[C#] vshosting.exe 가 뭘까요?  (0) 2012.03.26
[C#] Dynamic Method Call With Out Parameter  (0) 2012.03.22
[즐겨찾기] C# TreeView MultiSelect  (0) 2012.03.15
posted by 뚱2

[XtraGrid] DevExpress XtraGrid

.Net/XtraGrid 2012. 3. 28. 22:26

'.Net > XtraGrid' 카테고리의 다른 글

[XtraGrid] Online Document  (0) 2012.04.13
[XtraGrid] Copy & Paste 구현  (0) 2012.04.11
[XtraGrid] How to make my grid columns read-only  (0) 2012.04.08
[XtraGrid] Checkbox 구현하기  (1) 2012.04.06
[XtraGrid] Fixed Columns  (0) 2012.04.05
posted by 뚱2

[C#] vshosting.exe 가 뭘까요?

.Net/C# 2012. 3. 26. 14:27
WinForm으로 프로그램을 생성하면은 출력 디렉토리에 XXX.vshosting.exe 파일이 생성됩니다.
이게 궁금해서 찾아보니 잘 설명된 블로그가 있어서 링크 걸어둡니다.

링크 : http://blog.naver.com/saltynut?Redirect=Log&logNo=120017351107 

'.Net > C#' 카테고리의 다른 글

[C#] VS 2008 서식 자동 해제  (0) 2012.04.06
[C#] log4net  (0) 2012.04.03
[C#] Dynamic Method Call With Out Parameter  (0) 2012.03.22
[즐겨찾기] C# TreeView MultiSelect  (0) 2012.03.15
[C#] internal 지정자  (0) 2012.03.12
posted by 뚱2
C# ASP.NET 아티클 이지만 윈폼 응용프로그램에서도 유용하게 사용할수 있다.

링크 : http://www.primaryobjects.com/CMS/Article81.aspx 
posted by 뚱2
해당 오프젝트의 타입을 확인하고 메소드가 존재하고 파라미터가 일치한다면
호출해 준다.

// class
public class MyObject
{
    pub int Connect()
    {
        // 접속 ...
    }
    public void GetLastError(out int errorCode, out string errorMessage)
    {
        // 내부 코드들 ...
    }
}


    // ErrorUtil
    public class ErrorUtil
    {
        private static readonly string methodName = "GetLastError";
        private static int errorCode = 0;
        private static string errorMessage = "";

        public static int ErrorCode
        {
            get { return errorCode; }
        }

        public static string ErrorMessage
        {
            get { return errorMessage; }
        }

        public static bool GetLastError(object obj)
        {
            try
            {
                Type t = obj.GetType();
                MethodInfo info = t.GetMethod(
                    ErrorUtil.methodName,
                    BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
                    null,
                    new[] 
                    {
                        typeof(int).MakeByRefType(),
                        typeof(string).MakeByRefType()
                    },
                    null
                );

                if (info != null)
                {
                    object[] parameters = new object[2];
                    info.Invoke(obj, parameters);

                    errorCode = (int)parameters[0];
                    errorMessage = (string)parameters[1];
                    return true;
                }
                else
                {
                    errorMessage = String.Format("{0} 메소드를 찾을수 없거나, 파라미터가 정확하지 않습니다.", ErrorUtil.methodName);
                    return false;
                }
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
                return false;
            }
        }
    }


// 사용예
    MyObject oCommpany = new MyObject();
    int retCode = oCompany.Connect();
    if (retCode != 0)
    {
           ErrorUtil.GetLastError(oCompany);
           MessageBox.Show(ErrorUtil.ErrorMessage);
    }


'.Net > C#' 카테고리의 다른 글

[C#] log4net  (0) 2012.04.03
[C#] vshosting.exe 가 뭘까요?  (0) 2012.03.26
[즐겨찾기] C# TreeView MultiSelect  (0) 2012.03.15
[C#] internal 지정자  (0) 2012.03.12
[즐겨찾기] 무료서적 Inside C# 2nd  (0) 2012.03.10
posted by 뚱2

[C#] .Net Control.Invoke

.Net/.Net 2012. 3. 18. 20:17
MFC로만 응용프로그램을 만들어오다 이번에 프로젝트로 C# WinForm으로 응용프로그램을 만들게 되었다.
다른걸 떠나서 생산성 하나는 끝내준다.

각설하고 기본적으로 UI컨트롤은 메세지 루프로 이벤트를 받기때문에 메인 윈도우에서 생성해줘야 한다.
물론 별도 스레드를 만들고 메세지 루프도 만들어주면 가능하기는 한데 이건 된다 이거지 이렇게 사용해본적도
없고 본적도 없다.

백그라운드 작업을 할때 별도의 스레드에서 작업을 하고 메인 스레드에서 프로그레스 바를 이용해서 상태값을
변경해주는 방법을 종종 사용하는데 이게 네이티브 응용프로그램에서는 메세지로 컨트롤 했는데 
.Net쪽에서는 Controls.Invoke를 사용해서 해결한다는걸 삽질끝에 알았다.

Invoke 설명 : http://msdn.microsoft.com/ko-kr/library/system.windows.forms.control.invoke.aspx



위 이미지 같이 각 파일의 복사 나 이동의 상태를 알려주고 아래 프로그래스 바는 전체 파일 단위의 상태를 알려준다.

form code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Security.AccessControl;
using System.Threading;

namespace TestExplorer
{
    public partial class FileProgressForm : Form
    {
        public enum ACTION_TYPE {COPY, MOVE}
        delegate void SetProgressValueDelegate(int value);
        delegate void SetLabelTextDelegate(string text);
        delegate void DoEndDelegate();

        private string sourcePath = "";
        private string targetPath = "";
        private byte[] buffer = new byte[1024*100];// 100Kb
        private Thread thread = null;
        private ACTION_TYPE action = ACTION_TYPE.COPY;
        private bool isThreadEnd = false;

        public string SourcePath
        {
            get { return sourcePath;  }
            set { sourcePath = value; }
        }

        public string TargetPath
        {
            get { return targetPath; }
            set { targetPath = value; }
        }

        public ACTION_TYPE Action
        {
            get { return (action); }
            set { action = value;  }
        }

        public FileProgressForm()
        {
            InitializeComponent();
        }

        private void FileProgressForm_Load(object sender, EventArgs e)
        {
        }

        private void DoEnd()
        {
            this.isThreadEnd = true;
            this.DialogResult = DialogResult.OK;
        }

        private void FileProgressForm_Shown(object sender, EventArgs e)
        {
            // 파일 읽기 작업을 시작한다.
            if (File.Exists(this.sourcePath) == false
                && Directory.Exists(this.targetPath) == false)
            {
                MessageBox.Show("원본 폴더나, 파일을 선택해 주세요.");
                this.DialogResult = DialogResult.Cancel;
                return;
            }

            if (Directory.Exists(this.targetPath) == false)
            {
                MessageBox.Show("대상 폴더를 선택해 주세요.");
                this.DialogResult = DialogResult.Cancel;
                return;
            }

            if (this.sourcePath.Equals(this.targetPath) == true)
            {
                MessageBox.Show("원본과 대상이 일치합니다.");
                this.DialogResult = DialogResult.Cancel;
                return;
            }

            thread = new Thread(new ThreadStart(WorkThread));
            thread.Start();
        }

        // 복사 작업을 한다.
        private void WorkThread()
        {
            FileInfo[] arrfileInfo = null;

            if (File.Exists(sourcePath) == true)
            {
                arrfileInfo = new FileInfo[] { new FileInfo(sourcePath) };
            }
            else if (Directory.Exists(sourcePath) == true)
            {
                DirectoryInfo dirInfo = new DirectoryInfo(sourcePath);
                arrfileInfo = dirInfo.GetFiles();
            }

            if (arrfileInfo != null)
            {
                int count = arrfileInfo.Length;
                long total_current = 0;
                long total_total = 0;

                // 총 파일 용량을 가져온다.
                foreach (FileInfo i in arrfileInfo)
                {
                    if ((i.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden)
                    {
                        total_total += i.Length;
                    }
                }

                // 복사할 파일을 순회한다.
                foreach (FileInfo i in arrfileInfo)
                {
                    if ((i.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                    {
                        continue;
                    }

                    FileStream rs = null, ws = null;
                    try
                    {
                        rs = new FileStream(i.FullName, FileMode.Open);
                        ws = new FileStream(targetPath + "\\" + i.Name, FileMode.Create);

                        // 익명 메서드
                        this.Invoke((SetLabelTextDelegate)delegate(string text)
                        {
                            this.label_filename.Text = text;
                        },
                        new object[] {i.Name});


                        int readSize = 0;
                        long current_current = 0;
                        long current_total = i.Length;

                        while ((readSize = rs.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            current_current += readSize;
                            total_current += readSize;
                            // 현재 프로그래스 바
                            int percent = (int)((double)current_current / (double)current_total * 100);

                            Console.WriteLine("cur={0}, total={1}, percent={2}", current_current, current_total, percent);

                            //익명 메서드
                            this.Invoke((SetProgressValueDelegate)delegate(int value)
                            {
                                this.progressCur.Value = value;
                                this.lableCurPercent.Text = String.Format("{0}%", value);
                            },
                            new object[] {percent});

                            // 토탈 프로그래스 바
                            percent = (int)((double)total_current / (double)total_total * 100);
                            
                            //익명 메서드
                            this.Invoke((SetProgressValueDelegate)delegate(int value)
                            {
                                this.progressTotal.Value = value;
                                this.labelTotalPercent.Text = String.Format("{0}%", value);
                            },
                            new object[] { percent });


                            ws.Write(buffer, 0, readSize);
                        }//while ((readSize = rs.Read(buffer, 0, buffer.Length)) != 0)

                        //익명 메서드
                        this.Invoke((SetProgressValueDelegate)delegate(int value)
                        {
                            this.progressCur.Value = value;
                            this.lableCurPercent.Text = String.Format("{0}%", value);
                        },
                        new object[] { 100 });
                    }
                    catch (Exception ex)
                    {
                    }
                    finally
                    {
                        try { rs.Close(); }
                        catch (Exception ex) { }
                        try { ws.Close(); }
                        catch (Exception ex) { }
                    }

                    if (this.action == ACTION_TYPE.MOVE)
                    {
                        File.Delete(i.FullName);
                    }
                }//foreach (FileInfo i in arrfileInfo)

                //익명 메서드
                this.Invoke((SetProgressValueDelegate)delegate(int value)
                {
                    this.progressTotal.Value = value;
                    this.labelTotalPercent.Text = String.Format("{0}%", value);
                },
                new object[] { 100 });

                //TODO: 500 밀리세컨 슬립한다.
                Thread.Sleep(500);
            }//if (arrfileInfo != null)
            this.Invoke((DoEndDelegate)delegate()
            {
                this.DoEnd();
            });
        }//private void WorkThread(object arg)

        private void FileProgressForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (thread != null && thread.IsAlive == true && isThreadEnd == false )
            {
                MessageBox.Show("작업 중입니다.");
                e.Cancel = true;
            }
        }
    }
}


designer code
namespace TestExplorer
{
    partial class FileProgressForm
    {
        /// 
        /// Required designer variable.
        /// 
        private System.ComponentModel.IContainer components = null;

        /// 
        /// Clean up any resources being used.
        /// 
        /// true if managed resources should be disposed; otherwise, false.
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// 
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// 
        private void InitializeComponent()
        {
            this.progressCur = new System.Windows.Forms.ProgressBar();
            this.progressTotal = new System.Windows.Forms.ProgressBar();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.labelTotalPercent = new System.Windows.Forms.Label();
            this.lableCurPercent = new System.Windows.Forms.Label();
            this.label_filename = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // progressCur
            // 
            this.progressCur.Location = new System.Drawing.Point(13, 49);
            this.progressCur.Name = "progressCur";
            this.progressCur.Size = new System.Drawing.Size(366, 32);
            this.progressCur.Step = 1;
            this.progressCur.TabIndex = 0;
            // 
            // progressTotal
            // 
            this.progressTotal.Location = new System.Drawing.Point(12, 107);
            this.progressTotal.Name = "progressTotal";
            this.progressTotal.Size = new System.Drawing.Size(366, 32);
            this.progressTotal.Step = 1;
            this.progressTotal.TabIndex = 1;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(13, 32);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(65, 12);
            this.label1.TabIndex = 2;
            this.label1.Text = "현재 파일 :";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(13, 91);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(65, 12);
            this.label2.TabIndex = 3;
            this.label2.Text = "전체 파일 :";
            // 
            // labelTotalPercent
            // 
            this.labelTotalPercent.AutoSize = true;
            this.labelTotalPercent.Location = new System.Drawing.Point(87, 91);
            this.labelTotalPercent.Name = "labelTotalPercent";
            this.labelTotalPercent.Size = new System.Drawing.Size(21, 12);
            this.labelTotalPercent.TabIndex = 4;
            this.labelTotalPercent.Text = "0%";
            // 
            // lableCurPercent
            // 
            this.lableCurPercent.AutoSize = true;
            this.lableCurPercent.Location = new System.Drawing.Point(87, 32);
            this.lableCurPercent.Name = "lableCurPercent";
            this.lableCurPercent.Size = new System.Drawing.Size(21, 12);
            this.lableCurPercent.TabIndex = 5;
            this.lableCurPercent.Text = "0%";
            // 
            // label_filename
            // 
            this.label_filename.AutoSize = true;
            this.label_filename.Location = new System.Drawing.Point(13, 9);
            this.label_filename.Name = "label_filename";
            this.label_filename.Size = new System.Drawing.Size(75, 12);
            this.label_filename.TabIndex = 7;
            this.label_filename.Text = "(현재파일명)";
            // 
            // FileProgressForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(391, 151);
            this.Controls.Add(this.label_filename);
            this.Controls.Add(this.lableCurPercent);
            this.Controls.Add(this.labelTotalPercent);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.progressTotal);
            this.Controls.Add(this.progressCur);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "FileProgressForm";
            this.Text = "파일전송";
            this.Load += new System.EventHandler(this.FileProgressForm_Load);
            this.Shown += new System.EventHandler(this.FileProgressForm_Shown);
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FileProgressForm_FormClosing);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.ProgressBar progressCur;
        private System.Windows.Forms.ProgressBar progressTotal;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label labelTotalPercent;
        private System.Windows.Forms.Label lableCurPercent;
        private System.Windows.Forms.Label label_filename;
    }
}

 
posted by 뚱2