'MS Dev./KB'에 해당되는 글 22건

  1. 2009.06.21 업종별 표준 업무 프로세스 모델
  2. 2009.04.30 DataTable DataSet DataView Method
  3. 2009.04.13 각종 인터넷 에러메시지
  4. 2009.04.11 Training Kit
  5. 2009.03.27 처음으로 T옴니아폰 응용프로그램을 개발하려면?
  6. 2009.03.04 센티미터를 픽셀로 바꾸기
  7. 2009.03.03 정규식을 이용한 숫자입력 체크 함수
  8. 2009.02.16 바코드 출력 사이트 링크
  9. 2009.02.16 VSTO에서 메세지 서브클래싱..
  10. 2009.02.16 SQL Server 2005 Database Backup and Restore using C# and .NET 2.0
2009. 6. 21. 15:36

업종별 표준 업무 프로세스 모델


중소기업기술정보진흥원에서는 전통산업의 e-Manufacturing 및 e-Industry를 촉진하기 위해 업종별로 생산 방식 및 경영형태가 유사한 분야의 업무 프로세스를 표준화하여 2001년도부터 3년동안 총 20개 업종에 대한 표준모델을 개발하여 업종별 업무프로세스 표준모델을 제공하고 있습니다.

◆ 업종별 표준 업무 프로세스 모델

-1차년도 원문보기
  통신기기/방송장비
  반도체/전자부품
  전기기계
  자동차 부품
  식품 가공
  의약품/화학

-2차년도 원문보기
  고무/플라스틱 제조업
  제1차 금속산업
  조립금속 제품 제조업
  일반기계
  특수기계
  공통(인사/회계)

-3차년도 원문보기
  컴퓨터/사무기기 제조업
  선박 및 보트 제조업
  석유 정제품
  봉제/의복 제조업
  골판지/종이 제조업
  기초 화합물 제조업
  물류 서비스업
  제과 제조업
  유통 서비스업
  공통(인사/회계)

◆ 표준모델 적용 방법론
    중소기업기술정보진흥원에서 프로세스 모델을 도출하기 위하여 사용된 연차별
    프로세스 모델링 방법론
    - 1차년도 적용 방법론
    - 2차년도 적용 방법론
    - 3차년도 적용 방법론
    - 웹 개발 방법론


2009. 4. 30. 19:31

DataTable DataSet DataView Method


DataSet 으로 가져온 데이터를 기반으로 추가로 데이터를 가공할 경우가 필요해서 정리함.

http://www.codeguru.com/forum/showthread.php?t=332574

    DataSet ds = RepeaterProductInfo.DataSource as DataSet;
    DataRow [] row = ds.Tables[0].Select("Sum(ItemPrice)");
    strReturnValue = row[0][0].ToString();
    DataSet ds = RepeaterProductInfo.DataSource as DataSet;
    DataRow [] row = ds.Tables[0].Select("ItemPrice = Sum(ItemPrice)");
    strReturnValue = row[0][0].ToString();

DataTable.Compute Method
private void ComputeBySalesSalesID(DataSet dataSet)
{
    // Presumes a DataTable named "Orders" that has a column named "Total."
    DataTable table;
    table = dataSet.Tables["Orders"];

    // Declare an object variable.
    object sumObject;
    sumObject = table.Compute("Sum(Total)", "EmpID = 5");
}


Repeater Control and Data Binding - ASP .Net and C#

Introduction:

 Data Binding is the process of creating a link between the data source and the presentation UI to display the data. ASP .Net provides rich and wide variety of controls which can be bound to the data. This model of binding data with the data source reduces a lot of code complexity and increases the ease of maintenance of code. This article looks at how to use this data binding feature for a Repeater control in ASP .Net with C# code.

Repeater Control in ASP .Net:

   A Repeater control is a light weight control which can be used for simple reporting purposes. It supports basic event-handling like Init, Load, Unload etc., This also supports some basic formatting of data and can be presented to the user. A Repeater control offers limited level of data editing or selecting capabilities. For such editing and updates ASP .Net offers DataList and DataGrid controls.

   A Repeater control can be used to build small and Flexible reports with the templates for the items. It supports the following five templates.

  • HeaderTemplate : Can be used to create the Header Rows of the Table data being presented by Repeater control.
  • FooterTemplate : Can be used to create the Footer Rows of the Table data being presented by Repeater control.
  • ItemTemplate : Used for formatting the Items and rows to be displayed.
  • AlternatingItemTemplate : Alternating items formatting.
  • SeparatorTemplate : Styles for separating rows and columns.

   There are many ways in which a control in ASP .Net can be formatted. It is up to the imagination of the programmer to come up with nice formats. For example the Footer rows can be manipulated in such a way that, it can show the summary values or totals etc.,

Repeater Syntax:

<asp:Repeater id="idrepeater" runat="server" Datasource="<%# dataset %>" DataMember="table-inside-dataset">
<HeaderTemplate>..Header Format ..</HeaderTemplate>
<ItemTemplate> .. Item formats .. </ItemTemplate> 
</asp:Repeater>

    As given above, the syntax is simply the Repeater tag with the Template types. These templates can be formatted with ItemStyle tags also.

Using DataBinder.Eval method:

   The System.Web.UI.DataBinder class provides a useful static method DataBinder.Eval, which can be used to evaluate the data at run time using late binding. This function can be used with the Visual Studio IDE or can be manually coded as

 

<%#  DataBinder.Eval(Container.DataItem,"FieldName","Format") %>

   This evaluates and returns the data at run time. This can be used with Repeater, DataList and DataGrid controls though there will be a performance penalty because of the late binding mechanism used.

Creating a Sample Program with Repeater Control:

   Let's create a small sample program with the Repeater control. 

  1. Add a new Webform in an Visual Studio  Asp .net application.
  2. Add a Repeater control to the application. Let us assume that the id of the control is Repeater1.
  3. Insert the following lines of formatting code in between the opening and closing tags of the <asp:Repeater> control.
  4. <HeaderTemplate>
    <table cellpadding="5" cellspacing="2" >
    <tr bgcolor=Gray>
    <td><b>CustomerName</b></td>
    <td><b>Country</b></td>
    </tr>
    </HeaderTemplate>
    <ItemTemplate>
    <tr>
    <td><%# DataBinder.Eval(Container.DataItem,"CustomerName") %></td>
    <td><%# DataBinder.Eval(Container.DataItem,"Country") %></td>
    </tr>
    </ItemTemplate>
    <AlternatingItemTemplate>
    <tr bgcolor="#ccccff">
    <td><%# DataBinder.Eval(Container.DataItem,"CustomerName") %></td>
    <td><%# DataBinder.Eval(Container.DataItem,"Country") %></td>
    </tr>
    </AlternatingItemTemplate>
    <FooterTemplate>
    </table>
    </FooterTemplate>
  5. The above code just adds the repeater control with formatting for the header rows, data rows and the footer rows. The HeaderTemplate starts the <table> tag with the table heading and the FooterTemplate closes it.
  6. Now, Add the following code inside the Webform1.aspx.cs, Page_Load event.
    DataSet ds = new DataSet();
    DataTable dt = ds.Tables.Add("Customer");
    dt.Columns.Add("CustomerName",Type.GetType("System.String"));
    dt.Columns.Add("Country",Type.GetType("System.String"));

    DataRow dr = dt.NewRow();
    dr[0]="Testcustomer1";
    dr[1]="USA";
    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr[0]="Testcustomer2";
    dr[1]="UK";
    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr[0]="Testcustomer3";
    dr[1]="GERMANY";
    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr[0]="Testcustomer4";
    dr[1]="FRANCE";
    dt.Rows.Add(dr);

    //Bind the data to the Repeater
    Repeater1.DataSource = ds;
    Repeater1.DataMember = "Customer";
    Repeater1.DataBind();
  7. The above code creates a dataset to be used with the Repeater control. The repeater's datasource is the Dataset created and the Data member is mentioned as the Table which is created along with the dataset. This enables the Repeater to create the list of items from this customer table.
  8. Now build the application in Visual Studio .Net and load this page. The data will be shown in a tabular format.

   The above sample shows data binding from a statically created data set only. This can be very easily extended to a DataSet generated from database tables, xml files or even DataView s.

   Ultimately, this Repeater control can be used for light weight and simple report generation. This has only a very simple level event handling capabilities. Also there is a performance penalty because of using the DataBinder.Eval methods, this can be considered for data which are not modified frequently. If it is a large amount of data, then caching may be considered to improve the performance, though there are some other factors may have to be considered and not discussed here.

Attachments:

  Project Files : RepeaterSample.zip


Repeater Class


리피터 컨트롤 (Repeater Contorl) 사용시 빈 데이터 핸들링

강력하고 우아한 리피터 컨트롤을 가지고 빈데이터가 왔을경우 어떻게 표시할 수 있는지 그 처리를 위한 기본 메커니즘을 알아봅시다. 예를 들어 다른 컨트롤인 그리드 뷰 같은 경우, 바인드 되는 데이터가 비어있을 경우를 대비해서 그에 관한 속성을 지원합니다. (EmptyDataTemplate)
그렇지만 리피터 컨트롤에는 그와 같은 속성을 지원하지 않습니다. 다만, 리피터 컨트롤의 고유한 유연성으로 이 기능을 추가 시키기 쉽게 되어있습니다. 그럼 데이터가 비었을때 그와 관련된 메시지를 어떻게 나타내주는지 알아보도록 하겠습니다.

아래 예제는 리피터 컨트롤을 사용하여 테이블을 만들어 내는 코드 입니다.

<asp:Repeater runat="server" ID="Repeater1">
    <HeaderTemplate>
        <table width="80%">
    </HeaderTemplate>
    
    <ItemTemplate>
        <tr>
            <td><asp:Label runat="server" Text='<%# Eval("Model") %>' /></td>
        </tr>
    </ItemTemplate>
    
    <FooterTemplate>
        </table>
    </FooterTemplate>
</asp:Repeater>
 
if (!IsPostBack)
{
    List<Car> cars = new List<Car>();

    Repeater1.DataSource = cars;
    Repeater1.DataBind();
}

만약 위 코드에서 바인딩한 cars 에 빈값이 들어있다면 위 ItemTemplate는 사용되지 않고 리피터 컨트롤은 빈값을 나타내게 됩니다.  아래 코드는 그 결과입니다. Header와 Footer Template만 랜더링 되어있습니다.

<table width="80%">
            
</table>

위에서 보았듣이 Header나 Footer의 경우 데이터의 유/무와 상관없이 랜더링이 됩니다. 이를 이용하여 데이터를 기반으로 하여 빈 데이터시에 그 내용을 나타내 줄 수 있습니다.

아래 코드를 살펴 보겠습니다.

<table width="80%">
    <tr runat="server" 
        visible='<%# ((ICollection)Repeater1.DataSource).Count == 0 ? true : false %>'>
        <td>
            There is no data to display
        </td>
    </tr>

There are a couple of items that should be noted in the above example.

  • The Repeater has been referenced by it's  ID.
  • The DataSource property of the Repeater has been cast to an ICollection object. DataSource is defined as type object, but when data is bound to it, it must be of type ICollection. We are using the Count property from this interface to determine if the "Empty Data" message should display.

When there are several controls where the Visible property needs to be set, the logic can be moved to the code-behind for the page. This is shown in the following IsDataEmpty property.

protected bool IsDataEmpty
{
    get
    {
        ICollection list = Repeater1.DataSource as ICollection;

        return list.Count == 0 ? true : false;
    }
}

The ASPX will change to reference this property as follows:

<table width="80%">
    <tr runat="server" 
        visible='<%# IsDataEmpty %>'>
        <td>
            There is no data to display
        </td>
    </tr>

Regardless of which approach you use, the resulting HTML will now look like:

<table width="80%">
    <tr>
        <td>
            There is no data to display
        </td>
    </tr>   
</table>

As shown in the above examples, it is fairly simple to add HTML that will conditionally render based on the presence (or lack) of data bound to a Repeater.

출처 : http://devcenter.auburnrandall.com/Default.aspx?c=Tech&type=post&id=72


C# DataTable Group by Example

http://programming.top54u.com/post/C-sharp-DataTable-Group-by-Example.aspx

DataTable tbl1 = dset.Tables[0];

DataTable tbl2 = dset.Tables[1];

GridView1.DataSource = tbl2;
GridView1.DataBind();


int counter = 0;

// for each loop to group the records by categoryid
foreach (DataRow dr in tbl2.Rows)
{
    DataView dv = tbl1.DefaultView;
    dv.RowFilter = "categoryid=" + dr["categoryid"];

    GridView grd = (GridView)GridView1.Rows[counter].Cells[0].FindControl("GridView2");

    grd.DataSource = tbl1;
    grd.DataBind();

    counter++;
}




2009. 4. 13. 15:49

각종 인터넷 에러메시지


출처 : http://k.daum.net/qna/openknowledge/view.html?qid=2bzvR&q=%BF%A1%B7%AF&nil_no=29440

인터넷 에러메시지를 많이 보셨죠? 그 중에서 가장 대표적인 에러 메시지들을 소개합니다.

빠른 찾기는 ctrl+F 를 누르시면 됩니다.


▶ 403 Forbidden/Access Denied (403 금지/액세스 거부)

이 웹 사이트는 패스워드와 같은 특별한 액세스 승인을 필요로 하는
경우입니다.


▶ 404 Not Found (404 찾을 수 없음)

브라우저가 호스트 컴퓨터는 찾았으나 요청된 특정 도큐먼트를 찾지 못한 경우입니다.
정확한 주소를 입력했는지 확인해 봅니다. 그 페이지는 해당 웹 사이트에서 제거되었을 수도 있고 위치가 바뀌었을 수도 있습니다. 파일명을 떼어내고 주소를 다시 한 번 입력해 봅니다. 즉, 한 단계 위의 웹 사이트를 찾아 봅니다.

 

▶ 503 Service Unavailable (503 서비스 불가)

해당 웹 사이트의 서버에 과부하가 걸린 경우입니다.
몇 초 후에 다시 시도해 봅니다.

 

▶ Bad file request (잘못된 파일 요청)

온라인 폼 또는 HTML 코드가 잘못된 경우입니다.

 

▶ Connection refused by host (호스트의 접속 거부)

위에 있는 ‘403 Forbidden/Access Denied’ 에러와 유사한 상황입니다.

 

▶ Failed DNS lookup (DNS 찾기 실패)

해당 웹 사이트의 URL이 적절한 IP 주소로 전환될 수 없는 경우입니다.
이런 에러는 상용 사이트에서 빈번하게 발생하는데 IP 주소 전환을 담당하는 컴퓨터들이 과부하 상태에 놓이기 때문이라고 합니다.
물론, 주소를 잘못 입력한 경우에도 발생할 수 있습니다.
주소를 다시 한 번 입력해 보거나, 혼잡하지 않을 것 같은 시간에 다시 시도해 봅니다.

 

▶ Helper application not found

보조 응용프로그램(helper application)을 필요로 하는 파일을 다운받으려 하는데, 인터넷 익스플로러가 찾지 못하는 경우입니다.
이런 경우에는 아무 Windows 창이나 열어서 ‘보기(V)’의 ‘폴더 옵션(O)’에 있는 ‘파일 형식’ 탭을 선택하여 보조 응용프로그램을 위한 디렉토리 및 파일명이 정확하게 입력되도록 합니다.

 

▶ Not found (찾을 수 없음)

하이퍼링크가 가리키는 웹 페이지가 더 이상 존재하지 않음을 나타냅니다.

 

▶ Site unavailable (사이트 사용 불가)

너무 많은 사람들이 동시에 액세스하려 하면 온라인상에 노이즈가 생겨 해당 사이트가 다운될 수도 있고, 아니면 더 이상 그 사이트가 존재하지 않는 경우일 수도 있습니다. 주소를 잘못 입력해도 나올 수 있습니다.


▶ 각 Error 코드별 의미

100 : Continue
101 : Switching protocols
200 : OK, 에러없이 전송 성공
201 : Created, POST 명령 실행 및 성공
202 : Accepted, 서버가 클라이언트 명령을 받음
203 : Non-authoritative information, 서버가 클라이언트 요구 중 일부 만 전송
204 : No content, 클라언트 요구을 처리했으나 전송할 데이터가 없음
205 : Reset content
206 : Partial content
300 : Multiple choices, 최근에 옮겨진 데이터를 요청
301 : Moved permanently, 요구한 데이터를 변경된 임시 URL에서 찾았음
302 : Moved temporarily, 요구한 데이터가 변경된 URL에 있음을 명시
303 : See other, 요구한 데이터를 변경하지 않았기 때문에 문제가 있음
304 : Not modified
305 : Use proxy
400 : Bad request, 클라이언트의 잘못된 요청으로 처리할 수 없음
401 : Unauthorized, 클라이언트의 인증 실패
402 : Payment required, 예약됨
403 : Forbidden, 접근이 거부된 문서를 요청함
404 : Not found, 문서를 찾을 수 없음
405 : Method not allowed, 리소스를 허용안함
406 : Not acceptable, 허용할 수 없음
407 : Proxy authentication required, 프록시 인증 필요
408 : Request timeout, 요청시간이 지남
409 : Conflict
410 : Gone, 영구적으로 사용할 수 없음
411 : Length required
412 : Precondition failed, 전체조건 실패
413 : Request entity too large,
414 : Request-URI too long, URL이 너무 김
415 : Unsupported media type
500 : Internal server error, 내부서버 오류(잘못된 스크립트 실행시)
501 : Not implemented, 클라이언트에서 서버가 수행할 수 없는 행동을 요구함
502 : Bad gateway, 서버의 과부하 상태
503 : Service unavailable, 외부 서비스가 죽었거나 현재 멈춤 상태
504 : Gateway timeout
505 : HTTP version not supported

2009. 4. 11. 11:54

Training Kit

2009. 3. 27. 11:24

처음으로 T옴니아폰 응용프로그램을 개발하려면?


개발 환경 꾸미기를 한다면 다음과 같은 절차를 진행해 주시기를 권장합니다.

1. Windows XP Service Pack 2 또는 Windows Vista 운영체제 설치

1) Windows XP 서비스팩2 운영체제에서는 T옴니아폰과 PC와의 연결을 하기 위해서는 액티브 싱크(ActiveSync)가 필요합니다. 최신 버전은 4.5 입니다.

http://www.microsoft.com/downloads/details.aspx?displaylang=ko&FamilyID=9e641c34-6f7f-404d-a04b-dc09f8141141

2) Windows Vista 운영체제에서는 Windows Mobile Device Center 가 6.1 로 업데이트가 필요합니다.

http://www.microsoft.com/downloads/details.aspx?displaylang=ko&FamilyID=46f72df1-e46a-4a5f-a791-09f07aaa1914

2. 개발 도구로는 한글이든 영문이든 Visual Studio 2008 Professional Edition 이상이 있어야 합니다. 워크삽 때에는 Visual Studio Team System 평가판을 제공해 드렸습니다. 받지 못했거나 필요하신 분들은 아래의 URL에서 다운로드 받으실 수 있습니다. 

http://www.microsoft.com/downloads/details.aspx?FamilyID=83c3a1ec-ed72-4a79-8961-25635db0192b&DisplayLang=ko

단, Visual Studio Express 버전은 윈도우 모바일 응용 프로그램 개발을 지원하지 않습니다.

3. Visual Studio 2008 서비스 팩1을 설치해 주시기 바랍니다. .NET 프레임워크 3.5 및 WIndows Mobile 개발 컴포넌트를 업데이트 할 수 있습니다. 

http://www.microsoft.com/downloads/details.aspx?FamilyID=fbee1648-7106-44a7-9649-6d9f6d58056e&DisplayLang=ko

4. 이제 T옴니아폰에 필요할 Windows Mobile 6 Professional Edition SDK를 설치하면 됩니다. 이 SDK는 무료이고 T옴니아폰 외에 HTC 터치듀얼이라든가 SPH-4950 폰, 미라지 등과 같은 Windows Mobile 6 운영체제에서도 그대로 사용할 수 있습니다. 아래의 URL에서 다운로드 한 다음 설치해 주시기 바랍니다.

http://www.microsoft.com/downloads/details.aspx?FamilyID=06111a3a-a651-4745-88ef-3d48091a390b&DisplayLang=en

5. 원래 Windows Mobile 6 SDK 에는 영문(USA) 밖에 없다. 따라서 한글용 사용하기 위해서는 Windows Mobile 6 Emulator Localization Images 를 다운로드 받아야 합니다.

http://www.microsoft.com/downloads/details.aspx?FamilyID=38c46aa8-1dd7-426f-a913-4f370a65a582&DisplayLang=en

6. 마지막으로 Windows Mobile 6.1.4 Emulator Images (USA) 를 설치해 주면 되는데 여기에는 T옴니아 폰이나 HTC 터치 다이아몬드 HD 디스플레이 처럼 DPI 가 480 * 800 이미지가 포함 되어 있으므로 이를 다운로드 받아서 사용하는 것이 좋습니다.

http://www.microsoft.com/downloads/details.aspx?FamilyID=1a7a6b52-f89e-4354-84ce-5d19c204498a&DisplayLang=en

그 외 설치사항에 대해 궁금하신 분들은 댓글 남겨 주세요! 다음 번에 애플리케이션 개발 방법 종류에 대해서 적도록 하겠습니다.  

2009. 3. 4. 09:44

센티미터를 픽셀로 바꾸기

출처 : 나

익스플로러에서 인쇄물 출력 시 출력양식은 센티미터 기준이라서...
화면상에서 html로 그릴 때 pixel을 계산하기 위해서 만듬.



2009. 3. 3. 10:41

정규식을 이용한 숫자입력 체크 함수

내가 만든 숫자입력 체크 정규식
if (!Regex.IsMatch(txtInput.Text, @"^[0-9\.]*$"))
{
    // 숫자 아님
    txtInput.Text = string.Empty;
    txtInput.Select();                                                    
    return;
}
else
{
    // 숫자임
    fnCall();
}


* 단점 : 한글인 경우 체크가 안됩니다....ㅠㅠ

 

// 숫자, 콤마(,), 소숫점(.) 허용한 숫자체크

// 반환값 true / false

function IsNumber(strNumber)
{
    var reg = RegExp(/^(\d|-)?(\d|,)*\.?\d*$/);
    return reg .test(strNumber);
}


// IsNumber함수를 이용한 필드 입력값 체크

// 사용방법 : <input type="text" onkeyup="CheckNumber(this)">

function CheckNumber(field) {
   if( !IsNumber(field.value) )
   {
      alert!("숫자형식만 입력해주십시오.");
      field.value="0";
      field.focus();
      field.select();
   }
}

 

출처 : 몽키님 블로그

 (http://blog.daum.net/monkeychoi/4967162?srchid=BR1http%3A%2F%2Fblog.daum.net%2Fmonkeychoi%F4967162)

2009. 2. 16. 15:26

바코드 출력 사이트 링크

아래의 이미지 클릭하면 나오는 사이트는 텍스트 데이터를 바코드 이미지로 변경하여 준다.
샘플 이미지 및 바코드 출력물 테스트할 때 사용하면 됨.

가능한 바코드 타입 : Code39, Code128-A, Code128-B, Code128-C, UPC, EAN 등등

the barcode printer: free barcode generator

2009. 2. 16. 10:02

VSTO에서 메세지 서브클래싱..

출처 : http://handmade.egloos.com/3770543

한 몇일간 '졸작 주제를 잘못 잡은게 아닐까.. 이거 방법이 없는거 아냐?' 라는 생각에 밤잠 설치게(는 아니고 감기 걸려서 잠을 잘 못잤음..) 한 문제가 있었다. 그 문제는 바로!!

오피스 2007의 '리본X UI'에서 OfficeMenu(좌측 상단의 동그란 MS마크의 메뉴) 의 동작을 runtime 시에 동적으로 disable 시키고 싶었는데 그게 안되더라. 는 것이었다.

애초부터 안되는거 아니냐고? 설마! 그랬으면 내가 이런 일말의 희망을 가지고 이틀동안 인터넷을 떠돌아 다녔을리가 없다.
실제로 다음과 같이 리본 메뉴 스키마를 작성하면 disable 시킬수가 있다.

<?xml version="1.0" encoding="UTF-8"?>
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" onLoad="Ribbon_Load">
  <ribbon>
    <officeMenu>
      <button idMso="FileNew" enabled ="false"/>
    </officeMenu>

      <tabs>
      <tab idMso="TabAddIns">
        <group id="MyGroup"
               label="My Group">
          <toggleButton id="toy" label="연습" size="large" onAction="OnToggle" imageMso="HappyFace"/>
        </group>
      </tab>
    </tabs>
  </ribbon>
</customUI>
그럼됐지 뭐가 문제냐고? 저건 dynamic 하게 안된다는 무지막지한 단점이 있다. 즉 실행시에 한번만 초기화되면 어떻게 건들지를 못한다는거다.

근데.. 왠지 될거 같지 않은가? 왠지 모르게.. 저걸 읽어서 UI에 변화를 줄수 있다면 반대로 변화도 줄수 있을거야. MS가 나보다는 똑똑하니까, 분명히 무슨 함수라던지 속성이라던지가 있을꺼야.. 이러면서 이틀간 인터넷에서 사경을 헤멨(응?)..

근데, 암만 찾아봐도 dynamic하게 변경은 못하는것 같더라. 그래서 또 생각했다. 그러면 저 '리본 메뉴 스키마'를 2개(enable/disable)만들어 둬서 reload하면 될꺼야. 또 뒤졌다... 분명히 뭔가 있기는 있다. 그런데 이해가 안되더라. 
.NET 환경에서 작성된 내용도 아닌거 같고..(난 영어가 시러염!!!) 어쨌든 오늘도 그렇게 무료히 시간을 죽이고 있었더니..

invalidate라는 함수가 눈에 띄었다. (사실 어제부터 눈에 거슬렸으나.. 정확한 용법이 없으니 이게 뭘 하는지 모르겠는거라..)
MSDN을 뒤졌다. 오예~ 예제가 있다. 우선 살짝쿵 훑었다. 뭐 별거 없네.. 하고 닫으려는 순간 눈에 밟히는 문장이 있었으니..
[Instead of the Save dialog box appearing, the custom dialog box appears, as shown in Figure 2.]...

disable이 안된다면 내가 원하는대로 돌리면 되지(아놔.. '돼지' 야? '되지' 야?)..!!

그래서 결과 코드는 다음과 같이..
<?xml version="1.0" encoding="UTF-8"?>
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" onLoad="Ribbon_Load">
  <!-- QAT(Quick Access Toolbar) 부분 -->
  <commands>
    <command idMso="FileSave" onAction="MySave" />
  </commands>

  <ribbon startFromScratch="false">
    <!-- OfficeMenu 부분 -->
    <officeMenu>
      <button idMso="FileSave" enabled ="true" onAction ="MySave"/>
    </officeMenu>

    <tabs>
      <tab idMso="TabAddIns">
        <group id="MyGroup"
               label="My Group">
          <toggleButton description="this is test" id="toy" label="연습" size="large" onAction="OnToggle" imageMso="HappyFace"/>
        </group>
      </tab>
    </tabs>
  </ribbon>
</customUI>

    Dim repurposing As Boolean = False

    Public Sub MySave(ByVal control As Office.IRibbonControl, ByRef cancelDefault As Boolean)
        If (repurposing) Then
            System.Windows.Forms.MessageBox.Show("로컬 컴퓨터에 저장할수 없음.")
            cancelDefault = True
        Else
            cancelDefault = False
        End If

    End Sub

#Region "Smile Toggle Button Action"
    Public Sub OnToggle(ByVal control As Office.IRibbonControl, ByVal isPressed As Boolean)
        If (isPressed) Then
            ReportTaskPane.Visible = True
        Else
            ReportTaskPane.Visible = False
        End If
        repurposing = isPressed
        ribbon.Invalidate()
    End Sub
#End Region

referenced from: http://msdn2.microsoft.com/en-us/library/bb462633.aspx
2009. 2. 16. 09:59

SQL Server 2005 Database Backup and Restore using C# and .NET 2.0

출처 : http://www.codeproject.com/KB/database/SQL_Server_2005_Database.aspx

Introduction

The following article describes accessing a SQL Server 2005 database backup and restoring it programmatically using C#.NET 2.0 and SMO. This article provides coding samples to perform the task.

SQL Server Management Objects (SMO) is a collection of objects that are designed for programming all aspects of managing Microsoft SQL Server.

The following namespaces can be used to access SQL Server 2005 programmatically:

  • Microsoft.SqlServer.management
  • Microsoft.SqlServer.Management.NotificationServices
  • Microsoft.SqlServer.Management.Smo
  • Microsoft.SqlServer.Management.Smo.Agent
  • Microsoft.SqlServer.Management.Smo.Broker
  • Microsoft.SqlServer.Management.Smo.Mail
  • Microsoft.SqlServer.Management.Smo.RegisteredServers
  • Microsoft.SqlServer.Management.Smo.Wmi
  • Microsoft.SqlServer.Management.Trace

Pre-Requisite

You need to reference the following namespaces before using this code:

  • Microsoft.SqlServer.Management.Smo;
  • Microsoft.SqlServer.Management.Common;

I used these two class to perform the backup and restore operations:

  • Microsoft.SqlServer.Management.Smo.Backup
  • Microsoft.SqlServer.Management.Smo.Restore

For more information, regarding these two class, check MSDN:

Backup database

Collapse Copy Code
public void BackupDatabase(String databaseName, String userName, 
            String password, String serverName, String destinationPath)
{
    Backup sqlBackup = new Backup();
    
    sqlBackup.Action = BackupActionType.Database;
    sqlBackup.BackupSetDescription = "ArchiveDataBase:" + 
                                     DateTime.Now.ToShortDateString();
    sqlBackup.BackupSetName = "Archive";

    sqlBackup.Database = databaseName;

    BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath, DeviceType.File);
    ServerConnection connection = new ServerConnection(serverName, userName, password);
    Server sqlServer = new Server(connection);
    
    Database db = sqlServer.Databases[databaseName];
    
    sqlBackup.Initialize = true;
    sqlBackup.Checksum = true;
    sqlBackup.ContinueAfterError = true;
    
    sqlBackup.Devices.Add(deviceItem);
    sqlBackup.Incremental = false;

    sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
    sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;

    sqlBackup.FormatMedia = false;

    sqlBackup.SqlBackup(sqlServer);
}

Restore Database

Collapse Copy Code
public void RestoreDatabase(String databaseName, String filePath, 
       String serverName, String userName, String password, 
       String dataFilePath, String logFilePath)
{
    Restore sqlRestore = new Restore();
    
    BackupDeviceItem deviceItem = new BackupDeviceItem(filePath, DeviceType.File);
    sqlRestore.Devices.Add(deviceItem);
    sqlRestore.Database = databaseName;

    ServerConnection connection = new ServerConnection(serverName, userName, password);
    Server sqlServer = new Server(connection);

    Database db = sqlServer.Databases[databaseName];
    sqlRestore.Action = RestoreActionType.Database;
    String dataFileLocation = dataFilePath + databaseName + ".mdf";
    String logFileLocation = logFilePath + databaseName + "_Log.ldf";
    db = sqlServer.Databases[databaseName];
    RelocateFile rf = new RelocateFile(databaseName, dataFileLocation);
    
    sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName, dataFileLocation));
    sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName+"_log", logFileLocation));
    sqlRestore.ReplaceDatabase = true;
    sqlRestore.Complete += new ServerMessageEventHandler(sqlRestore_Complete);
    sqlRestore.PercentCompleteNotification = 10;
    sqlRestore.PercentComplete += 
       new PercentCompleteEventHandler(sqlRestore_PercentComplete);
            
    sqlRestore.SqlRestore(sqlServer);
    db = sqlServer.Databases[databaseName];
    db.SetOnline();
    sqlServer.Refresh();
}

The portion of code uses full backup features. If you want, you can perform incremental and differential backup as well.

Updates: June 8, 2008

In order to use this code, your SQL Server authentication mode needs to be configured as Mixed Mode authentication. If you use Windows Authentication, then you need to modify the ServerConnection:

Collapse Copy Code
SqlConnection sqlCon = new SqlConnection ("Data Source=Bappi; Integrated Security=True;");
ServerConnection connection = new ServerConnection(sqlCon);

Modify the ServerConnection portion of both code samples using this code in order to use Windows Security.

Conclusion

As this code uses the SQL Server 2005 backup/restore facility, the code follows the rules of SQL Server 2005 while backing up or restoring databases.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author