'Developer'에 해당되는 글 129건

  1. Routing WebForms OutBound
  2. 사용자 인터페이스의 Mockup을 만들어 주는 소프트웨어 79달러...
  3. JSLint 자바스크립트 검증해주는 웹사이트 1
  4. URL routing
  5. Response.RedirectPermanent()
  6. 일정 시간 후에 자동으로 컴퓨터 종료하기
  7. Visual Studio 2010 Betat 2 설치
  8. DataAdapter를 사용한 배치 업데이트 구현 방법
  9. ASP.NET 4.0 Quick Video Summary
  10. ASP.NET 4.0 Resource

Routing WebForms OutBound

목표: 텍스트 박스에 입력된 값으로 페이지 라우팅을 한다.


1. Global.asax 에서 라우팅 URL을 등록한다.


2. Default.aspx에서 텍스트박스와 버튼을 추가한다.

3. GetRouteUrl함수를 이용하여 텍스트 박스에서 받은 값으로 동적으로 라우팅 할 수 있다.

    Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim url As String = Page.GetRouteUrl("list-state", New With {.state = txtState.Text})
        Response.Redirect(url)
    End Sub
사용자 인터페이스의 Mockup을 만들어 주는 소프트웨어 79달러...

http://balsamiq.com/

JSLint 자바스크립트 검증해주는 웹사이트입니다. 개발한 자바스크립트 코드를 해당 웹사이트로 이동하여 텍스트박스에 붙여 넣고, 검증을 해볼 수 있습니다.

주소는 http://jslint.com 입니다. 비주얼스튜디오에 연동되는 플러그인도 제공을 하고 있습니다. http://jslint.codeplex.com 입니다.

URL routing


URL Routing

1. Add global.aspx
- add RegisterRoutes function


2. Add default.asxp

Add two linkbuttons as below


3. Add List.aspx
Add two labels. One of them will say the routhing values for "type".

list.aspx

list.aspx.vb



Response.RedirectPermanent()

Response.RedirectPermanent()

Response.Redirect는 302를 브라우져에게 되돌려 주는데, 이 뜻은 요청된 리소스가 임시적으로 다른 장소로 이동했다는 의미이다. 그러나 RedirectPermanent()는 301을 되돌려 주며,의미하는 바는 영원히 신규 페이지로 이동되었다는 것을 의미한다.

따라서, Response.Redirect를 사용하면 웹서치엔진(구글 같은)들은 이동하기전의 이전 페이지를 기록하며, RedirectPermanent()를 사용하면 이동된 신규 페이지를 기억하게 된다.

[VB.NET]
Protected Sub Application_BeginRequest(ByVal sender As Object, _
   
ByVal e As EventArgs)
   
    If Request.FilePath = "/our-products.aspx" Then
        Response.Redirect("/products.aspx", True)
    End If
    If Request.FilePath = "/about-us.aspx" Then
        Response.RedirectPermanent("/about.aspx", True)
    End If
End Sub


(참조)
http://weblogs.asp.net/gunnarpeipman/archive/2009/05/27/asp-net-4-0-seo-features-response-permanentredirect.aspx
시작->실행->tsshutdn [시간]

1시간 후에 종료하려면
Example) tsshutdn 3600


VS2010 Beta 2를 설치하는데 약 2시간 정도 소요되었다. 랩탑 사양은 듀얼코어 1.6이었다.

설치 도중에 2번정도 리부팅을 했다.

설치 후, 최초 기동시 약 10분 이상의 시간이 소요되었다.

웹프로젝트를 하나 생성했는데, 첫 느낌은 IDE의 User Interface의 면면이 너무 이뻤다.

영문 폰트가 이뻤다.

ASP.NET 웹 프로젝트를 생성했는데, 자동으로 로그인 페이지와 연관된 것들을 만들었으며, 메뉴도 만들어 졌다.

MVC 처음 시작했을 때와 비슷한 상황이다.

DataAdapter를 사용한 배치 업데이트 구현 방법


- DataAdapter를 이용해 데이트 베이스를 변경하려면 DataAdapter의 Update 메소드를 호출한다

When using Update, the order of execution is as follows:

  1. The values in the DataRow are moved to the parameter values.
  2. The OnRowUpdating event is raised.
  3. The command executes.
  4. If the command is set to FirstReturnedRecord, then the first returned result is placed in the DataRow.
  5. If there are output parameters, they are placed in the DataRow.
  6. The OnRowUpdated event is raised.
  7. AcceptChanges is called.

- DataRow 의 상태
public enum DataRowState
{
Detached = 1,
Unchanged = 2,
Added = 4,
Deleted = 8, 
Modified = 16
}

19t451d0.CFW(ko-kr,VS.90).gif19t451d0.xna(ko-kr,VS.90).gif Detached 행을 만들었지만 이 행은 DataRowCollection의 일부가 아닙니다. DataRow는 만들어진 직후 및 컬렉션에 추가되기 전 또는 컬렉션에서 제거된 경우 이 상태가 됩니다.
19t451d0.CFW(ko-kr,VS.90).gif19t451d0.xna(ko-kr,VS.90).gif Unchanged AcceptChanges를 마지막으로 호출한 이후 행이 변경되지 않았습니다.
19t451d0.CFW(ko-kr,VS.90).gif19t451d0.xna(ko-kr,VS.90).gif Added 행이 DataRowCollection에 추가되었으며 AcceptChanges는 호출되지 않았습니다.
19t451d0.CFW(ko-kr,VS.90).gif19t451d0.xna(ko-kr,VS.90).gif Deleted DataRow의 Delete 메서드를 사용하여 행을 삭제했습니다.
19t451d0.CFW(ko-kr,VS.90).gif19t451d0.xna(ko-kr,VS.90).gif Modified 행이 수정되었으며 AcceptChanges는 호출되지 않

Example)

Private Sub DemonstrateRowState()
    'Run a function to create a DataTable with one column.
    Dim dataTable As DataTable = MakeTable()
    Dim dataRow As DataRow

    ' Create a new DataRow.
    dataRow = dataTable.NewRow()
    ' Detached row.
    Console.WriteLine(String.Format("New Row {0}", dataRow.RowState))

    dataTable.Rows.Add(dataRow)
    ' New row.
    Console.WriteLine(String.Format("AddRow {0}", dataRow.RowState))

    dataTable.AcceptChanges()
    ' Unchanged row.
    Console.WriteLine(String.Format("AcceptChanges {0}", dataRow.RowState))

    dataRow("FirstName") = "Scott"
    ' Modified row.
    Console.WriteLine(String.Format("Modified {0}", dataRow.RowState))

    dataRow.Delete()
    ' Deleted row.
    Console.WriteLine(String.Format("Deleted {0}", dataRow.RowState))
End Sub

Private Function MakeTable() As DataTable
    ' Make a simple table with one column.
    Dim dt As New DataTable("dataTable")
    Dim firstName As New DataColumn("FirstName", _
       Type.GetType("System.String"))
    dt.Columns.Add(firstName)
    Return dt
End Function

DataRowVersion
Supported by the .NET Compact FrameworkSupported by the XNA Framework Original The row contains its original values.
Supported by the .NET Compact FrameworkSupported by the XNA Framework Current The row contains current values.
Supported by the .NET Compact FrameworkSupported by the XNA Framework Proposed The row contains a proposed value.
Supported by the .NET Compact FrameworkSupported by the XNA Framework Default The default version of DataRowState. For a DataRowState value of Added,Modified or Deleted, the default version is Current. For a DataRowState value ofDetached, the version is Proposed.

Private Sub DemonstrateRowState()
    'Run a function to create a DataTable with one column.
    Dim dataTable As DataTable = MakeTable()
    Dim dataRow As DataRow

    ' Create a new DataRow.
    dataRow = dataTable.NewRow()
    ' Detached row.
    Console.WriteLine(String.Format("New Row {0}", dataRow.RowState))

    dataTable.Rows.Add(dataRow)
    ' New row.
    Console.WriteLine(String.Format("AddRow {0}", dataRow.RowState))

    dataTable.AcceptChanges()
    ' Unchanged row.
    Console.WriteLine(String.Format("AcceptChanges {0}", dataRow.RowState))

    dataRow("FirstName") = "Scott"
    ' Modified row.
    Console.WriteLine(String.Format("Modified {0}", dataRow.RowState))

    dataRow.Delete()
    ' Deleted row.
    Console.WriteLine(String.Format("Deleted {0}", dataRow.RowState))
End Sub

Private Function MakeTable() As DataTable
    ' Make a simple table with one column.
    Dim dt As New DataTable("dataTable")
    Dim firstName As New DataColumn("FirstName", _
       Type.GetType("System.String"))
    dt.Columns.Add(firstName)
    Return dt
End Function

reate table TestTable (id int primary key, fname nvarchar(50), lname nvarchar(50))

 

insert into TestTable values (1, 'Mike', 'Spike')

insert into TestTable values (2, 'John', 'Johnson')

insert into TestTable values (3, 'Pete', 'Peterson')

 

--drop table TestTable

 

Then create a new C# Console application and run the following code:

 

        static void Main(string[] args)

        {

            string cs = @"Data Source=<your server>;Initial Catalog=<your database>;Integrated Security=SSPI";

            string sql = "SELECT id, fname, lname FROM TestTable";

 

            using (SqlConnection con = new SqlConnection(cs))

            {

                SqlDataAdapter da = new SqlDataAdapter(sql, con);

                DataTable dt = new DataTable("Persons");

                da.Fill(dt);

 

                Console.WriteLine("Rows are untouched...");

                ViewDataTableRowStatus(dt);

 

                // Modify a row.

                Console.WriteLine("Modifying the first row...");

                dt.Rows[0][1] = "Jake";

                ViewDataTableRowStatus(dt);

 

                // Add a row.

                Console.WriteLine("Adding a row");

                dt.Rows.Add(new object[]{100, "Paul""Paulson..."});

                ViewDataTableRowStatus(dt);

 

                // Now, if calling AcceptChanges() all rows will be set to Unchanged.

                Console.WriteLine("Calling AcceptChanges()...");

                dt.AcceptChanges();

                ViewDataTableRowStatus(dt);

 

                // This means that when we call update on the DataAdapter, it will return 0

                // since no rows has actuall been sent to the database. (first we need to build the INSERT and UPDATE commands)

                SqlCommandBuilder builder = new SqlCommandBuilder(da);

                da.InsertCommand = builder.GetInsertCommand();

                da.UpdateCommand = builder.GetUpdateCommand();

                int rows = da.Update(dt);

                Console.WriteLine("Updated rows: {0}", rows);

            }

        }

 

        private static void ViewDataTableRowStatus(DataTable dt)

        {

            foreach (DataRow dr in dt.Rows)

            {

                Console.WriteLine("Id:{0}\tFirstName: {1}\tRowState: {2}", dr[0].ToString(), dr[1].ToString(), dr.RowState.ToString());

            }

            Console.WriteLine();

        }



DataRowState와 DataRowVersion 이외에도 DataSet과 DataTable은 변경된 DataRow 객체들만을 별도의 DatSet혹은 DataTable로 구성해 주는 GetChanges 메서드도 있다.

UpdateBatchSize속성: 0이면 Sql Server Provider가 알아서 조정하며, 기본 값을 1이고 1이상이면 설정값의 횟수만큼 일괄 실행된다.

<MSDN 인용>
DataAdpater를 사용하여 배치 업데이트 수행

이전 버전의 ADO.NET에서는 데이터베이스를 DataSet의 변경 내용으로 업데이트하는 경우 DataAdapter의 Update 메서드에서 데이터베이스에 대해 한 번에 한 행씩 업데이트를 수행했습니다. 또한 지정한DataTable의 행에서 반복될 때 수정되었는지 여부를 확인하기 위해 각 DataRow를 검사했습니다. 행이 수정된 경우에는 해당 행의 RowState 속성 값에 따라 적절한 UpdateCommandInsertCommand또는 DeleteCommand를 호출했습니다. 그리고 행을 업데이트할 때마다 데이터베이스에 대한 네트워크 라운드트립이 수반되었습니다.

그러나 ADO.NET 2.0에서는 DataAdapter가 UpdateBatchSize 속성을 노출합니다. UpdateBatchSize를 양의 정수 값으로 설정하면 데이터베이스가 업데이트되어 지정된 크기의 배치로 전송됩니다. For example, setting the UpdateBatchSize to 10 will group 10 separate statements and submit them as single batch. UpdateBatchSize를 0으로 설정하면 DataAdapter가 서버에서 처리할 수 있는 최대 배치 크기를 사용합니다. 1로 설정할 경우에는 행이 한 번에 하나씩 전송되므로 배치 업데이트를 사용할 수 없습니다.

너무 큰 배치를 실행하면 성능이 저하될 수 있습니다. 따라서 응용 프로그램을 구현하기 전에 최적의 배치 크기 설정을 테스트해야 합니다.

UpdateBatchSize 속성 사용

When batch updates are enabled, the UpdatedRowSource property value of the DataAdapter's UpdateCommandInsertCommand, and DeleteCommand should be set to None orOutputParameters. 배치 업데이트를 수행하는 경우 명령의 UpdatedRowSource 속성 값 FirstReturnedRecord 또는 Both는 유효하지 않습니다.

다음 프로시저에서는 UpdateBatchSize 속성을 사용하는 방법을 보여 줍니다. 이 프로시저에서는 Production.ProductCategory 테이블의 ProductCategoryID 및 Name 필드를 표시하는 열이 포함된DataSet 개체와 배치 크기를 나타내는 정수(배치의 행 개수) 등 두 가지 인수를 사용합니다. 이 코드에서는 UpdateCommandInsertCommand 및 DeleteCommand 속성을 설정하여 새 SqlDataAdapter 개체를 만듭니다. 또한 DataSet 개체에 수정된 행이 있다고 가정합니다. 그리고 UpdateBatchSize 속성을 설정한 다음 업데이트를 실행합니다.

Visual Basic
Public Sub BatchUpdate( _
  ByVal dataTable As DataTable, ByVal batchSize As Int32)
    ' Assumes GetConnectionString() returns a valid connection string.
    Dim connectionString As String = GetConnectionString()

    ' Connect to the AdventureWorks database.
    Using connection As New SqlConnection(connectionString)
        ' Create a SqlDataAdapter.
        Dim adapter As New SqlDataAdapter()

        'Set the UPDATE command and parameters.
        adapter.UpdateCommand = New SqlCommand( _
          "UPDATE Production.ProductCategory SET " _
          & "Name=@Name WHERE ProductCategoryID=@ProdCatID;", _
          connection)
        adapter.UpdateCommand.Parameters.Add("@Name", _
          SqlDbType.NVarChar, 50, "Name")
        adapter.UpdateCommand.Parameters.Add("@ProdCatID",  _
          SqlDbType.Int, 4, " ProductCategoryID ")
        adapter.UpdateCommand.UpdatedRowSource = _
          UpdateRowSource.None

        'Set the INSERT command and parameter.
        adapter.InsertCommand = New SqlCommand( _
          "INSERT INTO Production.ProductCategory (Name) VALUES (@Name);", _
  connection)
        adapter.InsertCommand.Parameters.Add("@Name", _
          SqlDbType.NVarChar, 50, "Name")
        adapter.InsertCommand.UpdatedRowSource = _
          UpdateRowSource.None

        'Set the DELETE command and parameter.
        adapter.DeleteCommand = New SqlCommand( _
          "DELETE FROM Production.ProductCategory " _
          & "WHERE ProductCategoryID=@ProdCatID;", connection)
        adapter.DeleteCommand.Parameters.Add("@ProdCatID", _
           SqlDbType.Int, 4, " ProductCategoryID ")
        adapter.DeleteCommand.UpdatedRowSource = UpdateRowSource.None

        ' Set the batch size.
        adapter.UpdateBatchSize = batchSize

        ' Execute the update.
        adapter.Update(dataTable)
    End Using
End Sub

DataAdapter에는 업데이트 관련 이벤트인 RowUpdating 및 RowUpdated가 있습니다. 이전 버전의 ADO.NET에서 일괄 처리가 비활성화되어 있는 경우 각 이벤트는 처리되는 각 행마다 생성됩니다.RowUpdating은 업데이트가 발생하기 전에 생성되며 RowUpdated는 데이터베이스 업데이트가 완료된 뒤에 생성됩니다.

배치 업데이트에 따른 이벤트 동작 변경

일괄 처리가 활성화되면 한 번의 데이터베이스 동작으로 여러 개의 행이 업데이트됩니다. 따라서 RowUpdated 이벤트는 배치마다 한 번씩만 발생하지만 RowUpdating 이벤트는 행이 처리될 때마다 발생합니다. 일괄 처리가 비활성화되면 일대일 인터리빙으로 두 개의 이벤트가 발생합니다. 이 경우 RowUpdating 이벤트 하나와 RowUpdated 이벤트 하나가 한 행에 대해 발생한 후 모든 행이 처리될 때까지RowUpdating 및 RowUpdated 이벤트가 다음 행에 대해 하나씩 발생합니다.

업데이트된 행 액세스

일괄 처리가 비활성화되면 RowUpdatedEventArgs 클래스의 Row 속성을 사용하여 업데이트되는 행에 액세스할 수 있습니다.

일괄 처리가 활성화되면 여러 행에 대해 하나의 RowUpdated 이벤트가 생성됩니다. 따라서 각 행에 대한 Row 속성 값은 null입니다. RowUpdating 이벤트는 계속해서 각 행에 대해 생성됩니다.RowUpdatedEventArgs 클래스의 CopyToRows 메서드를 사용하면 행에 대한 참조를 배열에 복사하여 처리된 행에 액세스할 수 있습니다. 처리 중인 행이 없으면 CopyToRows에서ArgumentNullException이 throw됩니다. CopyToRows 메서드를 호출하기 전에 RowCount 속성을 사용하여 처리된 행 수를 반환합니다.

데이터 오류 처리

배치를 실행하면 각각의 개별 문을 실행하는 것과 동일한 효과가 나타납니다. 문은 배치에 추가된 순서대로 실행됩니다. 오류는 배치 모드가 비활성화되어 있는 상태와 동일하게 처리됩니다. 행은 각각 개별적으로 처리됩니다. 데이터베이스에서 성공적으로 처리된 행만 DataTable 내의 해당 DataRow에서 업데이트됩니다.

데이터 공급자 및 백 엔드 데이터베이스 서버는 배치 실행에 지원되는 SQL 구문을 결정합니다. 실행을 위해 지원되지 않는 문을 전송하면 예외가 throw될 수 있습니다.






ASP.NET 4.0 Quick Video Summary

1. Chart - 다양한 차트 컨트롤들이 추가되었다. 사용하기 쉽다.
2. MetaData - Page.MetaKeywords와 Page.MetaDescription를 이용하여 페이지에서 동적으로 메타 데이터를 설정하고, 이는 자동으로 HTML에 표시되어진다.

ASP.NET 4.0 Resource