ASP.NET에서 Page객체 내에 있는 IsPostBack과 IsCallBack의 차이를 명확히 몰랐다. 어떨때 Postback을 써야 할지, 어느 때 Callback을 써야 할지...

이제는 조금은 명확해져서 조심스럽게 포스트하도록 하겠다.

먼저 이 차이를 알려면, HTML을 이용한 서버 데이터 전송에 대해서 살펴보아야 할 것 같다.

예전 HTML로 작성된 데이터들은  정적 페이지라고 했다. 그 이유인 즉, 그 HTML 페이지에는 오로지 HTML 태그와 텍스트들로 나열되서 글과 그림 그리고 링크로 구성된 오로지 정보 전달만을 위한 페이지를 제공해 왔다. 그래서 당시 대부분의 홈페이지들은 텍스트와 이미지와 링크 만 있었고, 그나마 동적으로 움직이는 것을 움직이는 GIF나, 자바스크립트를 겨우 이용하는 정도 였다.  즐비했고, 사용자들은 서버에서 제공되는 값들을 이용만했지 절대 서버에 데이터를 주거나 하지 못했다.

그러다가, 이 HTML에 Form 이라는 것이 생겼다. 이 Form 내에 input 이라는 형태로 데이터들을 넣으면 form 내에 있는 각종 데이터들을 서버에 전달 할 수 있게 되었다. 아마 이 개념이 정립되면서 가입 양식 같은 형태로 만들 수 있었고, 이 가입양식 내에 데이터를 채우면 서버에 필요한 데이터를 전달할 수 있었다. 이 때 Form 안에 보면 action 이라는 속성 값으로 Html URL을 넘기게 되어있는데, 이 URL에 해당하는 서버로 데이터를 전송하게 된다. 이 때 부터 생긴 개념이 ghost 페이지라는 것이 생겼다. 이 ghost 페이지는 오로지 client에서 데이터를 받아 처리하는 로직만 담기고 실제로 사용자에게는 보여지지 않는 페이지였다.

이 개념을 ASP.NET에서 Postback이라는 것으로 만들었다. 즉 예전에는 총 3단계의 과정 [입력폼 페이지] -> [Ghost 페이지] -> [결과 페이지] 로 가졌던 것을 [입력폼 페이지] 하나만으로 그 Form 기능을 수행하게 하는 것이다.

ASP.NET에서 제공하는 System.Web.UI.WebControls 라는 네임 스페이스 안에 다양한 컨트롤들 Button, TextBox... 마치 Windows 클라이언트의 WinForm과 같은 컨트롤들을 생성해서 그 동작을 살펴보면 바로 저 Postback 개념으로 동작하는 것이다. 즉 예전 Form의 Post 방식으로 서버에 데이터를 전송하게 되는데, 단지 특정 Ghost 페이지가 아닌 자기 자신으로 다시 부르는 것이고, 이에 관련된 처리를 ASP.NET에서 자동으로 처리하는 것이다. 그래서 실제 프로그래밍 할 때는 Form 의 action이나, input 과 같은 태그 없이도 자동으로 클릭, 텍스트 변경 등의 이벤트에 대응되는 것이다.

그러나.... 이 방법은 큰 문제가 있으니, 바로 화면 Refresh이다. 이건 원래 Form의 Post 방식을 사용한 것이다 보니 Post가 발동 되는 순간 Form에 정의된 action의 페이지를 부르는 작업을 수행하는 것이다. 그 페이지가 다른 페이지던, 자기 자신이든 결국 그 페이지를 다시 부르는 것과 동일하기 때문에, 화면이 깜박이게 되는 것이다.

이 문제점에 대한 대안으로 callback이라는 것을 제공한다.
AJAX가 세상의 또하나의 트랜드가 되었을 때, 이번엔 HTTPRequest 라는 객체를 이용해 javascript로 데이터를 직접 읽어오는 로직을 ASP.NET으로 구현한 것이 바로 callback이라는 개념이다. 이 동작은 Form을 통해 데이터를 전달하는 것이 아니고 javascript가 독자적으로 httprequest 라는 모듈을 이용해 직접 페이지를 부르는 방법이기 때문에, 화면이 깜빡대지 않는다.


정리를 하자면, Postback은 옛날 개념, Callback은 근좌 유행한 AJAX 기반의 개념이라는 것. 그래서 일반적인 웹 컨트롤은 바로 Postback으로 체크하시면 되고, Callback은 ICallbackEvent 라는 인터페이스를 상속 받은 Page 객체 혹은 컨트롤에서 체크하면 된다.

728x90

관리도구 패널을 만들어야되는 시점. 우연히 켜 놓은 메신저를 통해 대구 동생(민수)이 넌즈시 건네준 말. "형 JQuery 알아요?".  예전에 문득 자바스크립트를 이용해서 XHTML에서 객체 Query 하는 기술인 줄 알고 답했더니, 피식 웃으며(물론 소리도, 모습도 보이지 않았지만, 그런 느낌?) JQuery 기술 관련 각종 URL과 문서를 건네주더군요.
자신이 만든 사이트와 함께 JQuery를 소개 시켜준 뒤 유유히 사라졌고(1년이나 지났는데 여전히 깨 쏟아져서 깨 볶아 먹는지 원....) 전 이 새로운 도구를 바라 보며, 먼 산 바라기를 했죠. 뭘 제대로 알아야지....

다행히 API 설명된 사이트를 알려줘서, 그 사이트에 적힌 내용을 하나씩 하나씩 보기 시작했습니다.(아.. 일어로 되어 있습니다 -_-;;) 그러나 역시 똥 한바가지 찬 제 머리로는 단빡에 이해되지 않았고, 다시 삽질 모드를 발동 했죠. 일단 지금 하던 작업과 연관 지어 Javascript 도배가 예상되는 그 페이지에 하나씩 하나씩 적용해 보기 시작했습니다..

왠걸.... 그 예전 Javascript 코드가 1/3 수준으로 줄고, 그 조작도 무척이나 편해져 버리더군요. 게다가 기능은 더욱더 풍부해진.....

이제 지금까제 제가 이해한 부분을 기반으로 이 JQuery를 소개하도록 하겠습니다.  단 Javascript로 자신이 직접 무언가를 짜기 보다는 네이년이나 다움을 통해 단순 Copy & Paste 수준에 머물고 있다면, 굳이 이 JQuery 세계를 이해하려 하는 만용은 조금 자제해 주세요.. 지금 부터 할 내용은 getElementById 라는 함수를 남발하고, AJAX를 좀 하면서, HTML 엘리멘트들을 이리 저리 옮기고 있는 분에게 새로운 도구를 GET 하시는 계기 정도의 글이 될 것 같군요. ( 물론 Javascript 전혀 몰라도, 그냥 읽어보는 것도 뭐 상관은 없지만 시간 낭비지 않을까 싶네요 (笑))

먼저 JQuery를 소개하기 앞서, JQuery가 가진 몇가지 장점들 중.... 제가 감동 먹은 베스트 2를 먼저 말씀드리겠습니다. 뭐 API나 각종 기능들의 소개는 다른 블로그들을 통해서 얻으실 수 있으니깐요. ㅋ

첫번째. null 걱정이 없다!

뭐 걍 직관적으로 javascript 짜시는 분들이야... 원래 신경 안썼다고 하시겠지만, 저 같이 결벽증이 있고, 뭐든 의심하고 보는 사람에게는 엄청난 스트레스 입니다.

예를 한번 들어보죠...

var linkbutton = doucment.getElementById("forNextPage");
linkbutton.style.display = "none";

라는 코드가 있을때... 과연 저 linkbutton 가 null 일까요? 아닐까요? 당연히 있으면 null은 아니겠지만, 만일에 저 "forNextPage" 부분이 변수로 처리되서 값을 만들어서 넣는다면? 과연 항상 null 이 아니라고 장담할 수 있을까요? 만일 null 이기만 하면, 바로 자바스크립트 오류 팍 뿜죠... 그게 걱정 된다고 밑에 if (linkbutton != null )을 넣기 시작하면 점점 코드가 점점 가관의 길을 걷게 됩니다.

자... 이걸 JQuery로 한다면....

$("#forNextPage").css("display", "none");

네.. 이 한줄입니다.  $("#forNextPage")가 null인지 아닌지 어떻게 아냐구요? 절대 null일리 없습니다. 단지, $("#forNextPage") 안에 객체가 있을까 없을까 정도이지, $("#forNextPage") 자체는 null 이 아닙니다. 만일 $("#forNextPage")로 JQuery 객체가 없다고 하면, 그냥 안이 비어 있는 JQuery 객체일 뿐입니다.  그래서 .css(.....) 부분은 실행되지 않고 끝나게 되겠죠. 믿어지지 않는다구요? 뭐 일단 제가 말씀드린 3가지 장점 설명 후에 JQuery 객체에 대해 제가 이해한 내용을 언급드리죠.

두번째, 다중 선택을 한줄로!!!

만일 <div> 라는 객체를 남발한다고 하죠. 그런데 그 div를 일괄적으로 색을 변경해야 된다고 할때... 어떻게 하시나요? 물론 다양한 방법이 있지만, 저 같은 경우에는 각 div 에 id를 할당 한뒤, 그 id를 기반으로 작업을 수행합니다.

예를 들어보죠....

<div id="parent001">
    <div id="display1"> 보여줍니다.</div>
    <div id="Rdisplay1" >이건 빨간색입니다.</div>
    <div id="display2"> 보여줍니다.</div>
    <div id="Rdisplay2" > 이건 빨간색입니다.</</div>
    <div id="display3"> 보여줍니다.</div>
    <div id="Rdisplay3" > 이건 빨간색입니다.</div>
    <div id="display4"> 보여줍니다.</div>
    <div id="Rdisplay4" >이건 빨간색입니다.</div>
    <div id="display5"> 보여줍니다.</div>
    <div id="Rdisplay5" > 이건 빨간색입니다.</div>
</div>

자 위와 같은 html이 있다고 하죠. 자 XHTML의 특징이 바로 저 id라는 항목인데, id는 전체 XHTML 내에서 고유하게 할당해 주어야 합니다. 뭐 저렇게 규칙적인 것은 Server-side-script 인, PHP나 ASP 또는 ASP.NET 으로 만들면 뭐 껌입니다. (껌이 쉬운지는 잘 모르겠지만요..)

자 위의 내용을 자바스크립트를 통해 "보여줍니다" 항목에 style을 모두 파란색으로 변경한다고 하죠.

예전 제가 했던 방식에 의거하면.. 이렇게 만들어지겠죠?

for(i=1; i<6;i++)  {
      document.getElementByIdl("display" + i).style.background-color = "Blue";
}

네 위와 같이 짰을 겁니다. 그러나.. 이 결벽증 어디로 갈까요? 다시 저 eval의 결과가 null 인지 아닌지 검사해야 합니다.

for(i=1; i<6;i++) {
      var target = document.getElementById("display" + i);
      if(target != null)
          target.style.background-color = "Blue";
}

3줄 짜리가 벌써 5줄로 거의 2배가 되버렸네요. 그래도 안전하면 뭐든지.. ㄷㄷㄷ

자.. 저것을.. JQuery로 승화시키면?

$("div[id^='display']").css("background-color","Blue");

조금더 다듬는다면,

$("#parent001']").children("div[id^='display']").css("background-color","Blue");

윗 줄은 전체 document에서 div를 모두 검색하되 단, id가 display로 시작하는 것을 검색하는 것이고, 두번째 줄은 parent001을 먼저 찾고, 그 하위에 있는 구성요소 중 div에서 id가 display로 시작하는 것을 찾는 것이죠.

for에 getElementById에 그것이 null인지 아닌지 ... 전혀 없고, 그냥 한줄로 끝납니다.

결론

정말 엄청난 녀석을 낚았다고나 할까요. 동생 덕에 근좌 자바스크립트 점점 간단해 지고 있습니다. ( 물론 동료들에게는 아직 알리지 않은 내용이니, 그 분들이 제 자바스크립트 소스를 보면 암호문 같아 당혹스러워 할 지는 모르겠습니다. -_-;;;;)

일단, 간단하게 제가 느낀 감상문을 먼저 적어보았고, 그 동안 제가 해보면서 느꼈던 각종 테크닉들을 정리해서 올려보도록 하겠습니다.

728x90

A 태그(<A>) 라든가, DIV 태그(<DIV>), 또는 SPAN 태그(<SPAN>)을 이용하여 안에 각종 Text를 넣을 수 있다. 그런데, 이 Text에 대한 설명이나 말을 줄여 놓으면 그 원래 크기의 문자열을 표시하고 싶을 때가 있다.

이 때 괜찮은 방법이 바로 툴팁이라는 조그만한 노란 창이 좋다. 이것을 사용하려면, 태그 안에 title 이라는 속성 내에 값을 넣어주면 된다.

다양한 Tag 내에서 속성 값으로 title 이라는 속성 값 내에 툴팁으로 표시하는 방법이다. 현재까지 테스트된 태그로는 <A> <DIV> <SPAN> 이며 이외에도 다양한 태그들 안에서 동작가능할 것 같다.

만일 특정 테이블 안에 Text에서 툴팁이 나오게 하기 위해서는 <span title="툴팁내용">test</span>  또는 <div title="툴팁내용">test</div> 라는 형태로 넣어주면 나오게 된다.

테스트 결과 FF 3.0과 IE 7.0 에서 정상적으로 표시된다.
(FF 2.X에는 어떤지는 잘 모르겠다.)

728x90

예전 포스팅 중 [ Javascript, 객체화 하기 ] 라는 제목으로 올린 것이 있다.
그 때 쓴 포스팅 방법에 의거해서 예제 소스를 하나 구성하면 아래와 같다.

var objTest = {
      valDisplay : "",
      displayValue : function () {
            alert(this.valDisplay);
      }
     
      setValue : function(val) {
            this.valDisplay = val;
      } 
};

위의 예제를 실행해 보려면, 적절한 위치에서 아래와 같은 코드를 실행해 보면 된다.

objTest.setValue("Go Go Objected Javascript World");
objTest.displayValue();

그런데, 위와 같은 코드를 하게 되면 문제가 하나 있다. 예를 들어 objTest와 같은 로직을 부르는 곳이 많을 때다. 여기서 부르는 곳이 많다는 의미를 단순히 호출 자체의 횟수가 아니고, valDisplay를 독립적으로 운영해야 되는 경우를 말하는 것이다.
예를 들어 아래와 같은 코드를 보도록 하자.

objTest0.setValue("Go Go Objected Javascript World");
objTest0.displayValue();
objTest1.setValue("No, I Want to new display valueGo Go Objected Javascript World");
objTest1.displayValue();

위와 같은 코드를 실행하려면 아래 처럼, 처음 코드를 두개 넣어야 한다.

var objTest0 = {
      valDisplay : "",
      displayValue : function () {
            alert(this.valDisplay);
      }
     
      setValue : function(val) {
            this.valDisplay = val;
      } 
};
var objTest1 = {
      valDisplay : "",
      displayValue : function () {
            alert(this.valDisplay);
      }
     
      setValue : function(val) {
            this.valDisplay = val;
      } 
};

처음에는 단순하게 생각했었다. objTest0 = objTest; objTest1 = objTest; 이렇게 하면 되지 않을까 하고....그런데, 그렇게 쉽게 되지는 않았다. 두개의 변수는 하나의 objTest를 바라보고 있어, 결국 값은 valDisplay를 공유한 꼴이 되버린 것이다.

이에 구글링과 테스트를 반복하여 그 방법을 드디어 찾아냈다.
즉 첫번째 소스를 이렇게 변경하면 된다.

objTest = function() {
     this.valDisplay = "";
     this.displayValue = function () {
            alert(this.valDisplay);
      }     
      this.setValue = function(val) {
            this.valDisplay = val;
      } 
};

실제 실행하는 코드는 아래 처럼 짜면 된다.

var objTest0 = new objTest();
objTest0.setValue("Test0 objTest!!!!");
var objTest1 = new objTest();
objTest1.setValue("Test1 objTest!!!!");

new 라는 것을 사용해서 만들기 때문에, 새로운 인스턴스가 생성되며 별개의 메모리 상에서 동작하게 되는 것이다. 이렇게 될 수 있는 건 자바스크립트의 미묘한 마법때문이다. 예전에 이런 문제 발생한적이 있지 않은가?

var realVar = "Init Data";
reelVar = "Update value!!!";
alert(realVar);

결과는 의도한 "Update value!!!"는 안찍히고 "Init Data"가 찍힌다. 그 이유는? reelVar 라는 변수 명이 잘못된 것이다. 그러나 씹고 그냥 진행되고 도리어 reelVar라는 변수가 하나 더 생기고 그 안에 값이 들어가 버린다. 맨 아랫줄에 alert(reelVar) 찍어보면 그제서야 "Update value!!!" 가 찍힌다. 자바 스크립트에서는 새로운 형태의 변수가 발견되면 일단 변수를 멋대로 만든다.

이런 기묘한 자바스크립트의 성질을 이용해 구성하는 것이다.
코드를 하나씩 뜯어 보도록 하자.

objTest = function() {      
};
일단 함수를 만드는 것이다. 함수 객체 자체를 objTest에 담는 것이다. 즉 objTest는 변수이긴 하지만 실제로 들어 있는 것은 함수인 것이다.
     this.valDisplay = "";
여기서 부터가 진짜 마법이다. this를 처음 접하신 분들은 순간 당황하실 것이고, 객체 지향을 하시던 분이라면 저 this가 어딜 가르키는 this인지 도무지 판단이 안서실 것이다. 저 this란 바로 function() 즉 objTest를 가르키는 것이다. 즉 objTest 라는 이름의 함수 내에 valDisplay 라는 변수를 정의하는 것이다. 이처럼 정의하는 이유는 아래의 또다른 함수의 형태 때문이다. 
     this.displayValue = function () {
            alert(this.valDisplay);
      }

이번에는 displayValue 라는 형안에 또다른 함수를 때려 박는다. 이 함수는 objTest.displayValue로 호출 된다. 그런데 만일 아까 this.valDisplay = ""; 가 아닌 var valDisplay = "" 라고 쓴다면 저 함수 안에서는 밖에서 정의한 변수를 쓸 수 없다. (물론 무한한 자바스크립트 세계에서 "완전 불가"/"절대" 란 없으니 "완전 불가"/"절대" 라는 말을 뺐다.) 즉 내부에서 사용하기 위한 변수로 쓰기 위해서 this. 라는 것을 붙여서 처리한 것이다.

여튼, 지금 필자는 MOSS 2007에 WebPart라는 개념이 있는데, AJAX 스럽게 만들려다 보니, 같은 스크립트를 여러 다른 웹파트들이 쓰게 되었는데, 일단 저렇게 간신히 해결하는데 성공했다. 미묘한 감동 찌리리링 상태다.

728x90

원본글 : http://weblogs.asp.net/haroonwaheed/archive/2008/06/30/ASP.NET-Performance-Tips.aspx

최고의 자료인듯.

ASP.NET Performance Tips

At times even after applying the best coding policies & practices you don’t get the desired level of performance you are hoping from your ASP.NET application. This is because there are number other very important factors that directly affect ASP.NET applications. To get the best out of any system requires detail architectural, design, coding and deployment considerations. The post lists few of some of the many performance tweaks that you can implement to boost up ASP.NET performance.

Remove Unused HTTP Modules

There are various HTTP modules in ASP.NET that intercept each request sent to the server. Session State is a very commonly used HTTP module used to load session data in context object. It’s referred with SessionStateModule name. HTTP modules kick in at each request and process them, therefore if you are not using the functionality provided by the module there is no use referring it as they would use additional CPU cycles. There is a list of HTTP Modules that your application automatically uses when it inherits config setting from web.config placed in $WindowsFolder\Microsoft.NET\Framework\$versiosn\CONFIG folder.
Below is a list of such entries:

<httpModules>
  <add name="OutputCache" type="System.Web.Caching.OutputCacheModule"/>
  <add name="Session" type="System.Web.SessionState.SessionStateModule"/>
  <add name="WindowsAuthentication" type="System.Web.Security.WindowsAuthenticationModule"/>
  <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule"/>
  <add name="PassportAuthentication" type="System.Web.Security.PassportAuthenticationModule"/>
  <add name="RoleManager" type="System.Web.Security.RoleManagerModule"/>
  <add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule"/>
  <add name="FileAuthorization" type="System.Web.Security.FileAuthorizationModule"/>
  <add name="AnonymousIdentification" type="System.Web.Security.AnonymousIdentificationModule"/>
  <add name="Profile" type="System.Web.Profile.ProfileModule"/>
  <add name="ErrorHandlerModule" type="System.Web.Mobile.ErrorHandlerModule, System.Web.Mobile, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
  <add name="ServiceModel" type="System.ServiceModel.Activation.HttpModule, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</httpModules>

There are bunch of HTTP modules listed here and I am quite positive not all of them are being used by your application. Removing unused HTTP module can definitely give slight performance boost as there would be less work to be performed. Suppose one doesn’t needs Windows authentication in application. To remove the inherited setting, under httpModules section in your web.config application add a remove element and specify name of the module that isn’t required.

Example:
      <httpModules>
            <remove name="WindowsAuthentication" />
      </httpModules>

<compilation debug=”true”/> Killer
As a developer I have seen numerous incidents were the application is deployed to production with <compilation debug=”true”/>. This is really a performance killer because:
  • Compilation of ASP.NET pages take longer.
  • Code execute slower as debug paths are enabled.
  • More memory is used by the application.
  • Scripts and images from WebResource.axd handler are not cached.

Always make sure that debug flag is set to false on production instances. You can override this by specifying following entry in machine.config for production instances:

      <configuration>
            <system.web>
                    <deployment retail=true/>
            </system.web>
      </configuration>

This will disable the <compilation debug=”true”/> for all applications deployed on the server.

Turn off Tracing

Do remember to turn off tracing before deploying application to production. Tracing adds additional overload to your application which is not required in production environment. To disable tracing use the following entries:

      <configuration>
            <system.web>
                    <trace enabled="false" />
            </system.web>
      </configuration>

Process Model Optimization
ASP.NET allows you to define many process level properties. You can get the detail of all these properties from http://msdn.microsoft.com/en-us/library/7w2sway1.aspx.  By default these are set to auto config. This means that ASP.NET automatically configures maxWorkerThreads, maxIoThreads, minFreeThreads, minLocalRequestFreeThreads and maxConnection to achieve optimal performance. You can tailor these by specifying your own value to achieve better performance. Some of the major settings are:
  • maxWorkerThreads. The default value is 20 per process and it determines the maximum number for request that ASP.NET can process in a given second. For application that are not CPU intensive and most of time wait on database request or any external processing this can increased to get better performance.
  • maxIOThreads. The default value is 20 per process and it determines the maximum number for I/O request that ASP.NET can process in a given second. If you have enough I/O resources you can increase this value for better results.
  • memoryLimit: The default is 60%. This is the max memory ASP.NET can use until worker process is refreshed. If you have a dedicated web server with no other services running you can increase this value for better results. 
  • connectionManagement: This is a property of System.Net configuration and specifies the maximum parallel connections that can be established to a server. If your web application extensively connects to other server you can increase this value.
Enable Buffering

Make sure that buffering is enabled unless you have a specific need to turn it off. By default its enabled. ASP.Net sends response to IIS in a 31 KB buffer which then passes that to the client. When buffering is disabled ASP.NET only sends few characters to IIS thus not utilizing this buffer and increasing the trips between IIS and the worker process. To enable it you can change the web.config or enable it on each page through @page directive

      <pages buffer="true">

      <%@ Page Buffer="true"%>

Caching
Caching in ASP.NET dramatically help in boosting application performance by reducing the load on the underlying server and serving cached content that doesn’t need to be recreated on each request. ASP.NET provides two types of caching:
  • Output Cache which stores dynamic pages and user controls. One each request code is not executed if a cached version of page or control is available 
  • Data Cache which allows application to save application objects, DataSet etc in server memory so they are not recreated on each request.

Use caching whenever possible to reduce the load on your web server and to increase response time.

Caching is a huge topic can not be discussed in detail in one post. For more details visit http://msdn.microsoft.com/en-us/library/xsbfdd8c.aspx.

Kernel Cache
Use Kernel Cache if you are using IIS 6 or above. When Output cache is used in ASP.NET the request still goes to ASP.NET that itself returns the cached content. However if Kernel Cache is enabled and the request is output cached by ASP.NET, IIS receives the cached content. If a request comes for that data again IIS will serve the cached content and end the response. This can save valuable CPU cycles as it minimizes work performed by ASP.NET.

Avoid using Response.Redirect
Instead of using Response.Redirect, use Server.Transfer where ever you can. Response.Redirect sends response to the client which then sends a new request to the server. Server.Transfer however performs the redirect on the server. Only use Response.Redirect when you want authentication and authorization to be performed on redirects or you want URL on client browser to be changed because Server.Transfer will not do this as it is a server side transfer.

Avoid using Server-Side Validation
Where ever you can use client-side validation instead of Server-Side validation. This will save you from additional reposts in cases in invalid input. If you don’t trust the browsers that they will be able to perform complex validations still use client-side validation and on repost check Page.IsValid to check if the input passed the given set of rules.

Avoid DataBinder.Eval Calls
Avoid calling DataBinder.Eval multiple times for example in case of grids, repeaters etc. Instead use Continer.DataBind. DataBinder.Eval uses reflection to evaluate the arguments and therefore can decrease performance if called numerous times.

Avoid Using Page.DataBind
Never call Page.DataBind until your really need to do so. Instead if you want to bind a specific control only bind that. Calling Page.DataBind will call DataBind for all the controls that support binding.

ViewState Optimization
Avoid using ViewState for storing huge objects or disable it when you don’t need it. ViewState is also used by server controls so that they can retain their state after postback. You can also save your objects that are marked Serializable in the ViewState. ASP.NET serializes all objects and controls in the ViewState and transmits them in a hidden field to the browser. If not managed properly ViewState can increase page size and therefore increase network traffic. Also precious CPU cycles are used for Serialization and De-Serialization of ViewState objects. Disable ViewState if:
  • Your pages don’t do postback.
  • You controls are not bound to a data source or they don’t handle server events like OnClick, OnSelectedIndexChanged etc or their properties are set on each postback
  • You recreate controls on every postback.

You can disable ViewState in both web.config or @Page directive

      <pages enableViewState="false">
      or
      <%@ Page EnableViewState="false"%>

Save or Compress ViewState
In case where ViewState in mandatory and the ViewState contains enough data that can cause Network congestion or increase download response time for the user try saving or compressing the ViewState. The Page class provide two very useful methods LoadPageStateFromPersistenceMedium() and SavePageStateToPersistenceMedium(object ViewState). You can override these methods to either compress the ViewState or even prevent it from going to the client by saving it in some persistent medium on the server.

Use HTTP Compression
If your page size is large enough to cause noticeable lag between subsequent request and response you can use HTTP compression. HTTP compression is a feature of IIS and what it means is that you can compress data sent to the client using compression techniques like GZIP and Deflate. On the other side the browser decompresses the data and shows the response to the client. Most of the modern browser are capable of handling compressed data. You will certainly get a huge performance boost if your page size is large.

For more details on HTTP compression visit http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/d52ff289-94d3-4085-bc4e-24eb4f312e0e.mspx?mfr=true

Data Paging / Sorting
When ever using data grid to show data with paging enabled one thing needs to understood that if your query returned let say 5000 record and you are only showing 100 records per page the rest of the 4900 record will be discarding and the same will apply when ever you will change the page or apply sorting. The additional 4900 rows will definitely take up memory and if your database is located on a different server which is most commonly the case you will also be transferring unnecessary data over the network. Make sure you are only returning the required results to the ASP.NET application by filtering out the data in your database query and apply custom paging. SQL Server 2005 and onwards provide valuable function for ranking data that can be used to accomplish this.

Connection Pooling
Creating a connection to a database is a resource intensive process and takes time. Connection pooling allows you to reuse these connections saving time and resources. When a new connection is requested the connection pool managers first searches in the connection pool and if doesn’t finds one, it creates a new one. There are various things that need to be done to use connection pooling effectively:
  • Avoid Connection Leakage. This means that you opened a connection but didn’t close it. If you don’t close the connection the connection pool manager will never put it in the pool for later reuse until the GC is called.
  • Use the same connection string. Connection pool manager searches for similar connection in the pool by the connection string.
  • Use SQL Servers and .NET CLR Data performance counters to monitor pooling.
  • Open connections as late as possible and close them as early as possible
  • Don’t share same connection between multiple function calls. Instead open a new connection and close it in each function.
  • Close transactions prior to closing the connection.
  • Keep at least one connection open to maintain the connection pool.

Avoid Multiple Database Access
Avoid accessing database multiple times for the same request. Analyze your code and see if you can reduce the number of trips to database because these trips reduce the number of request per second your application can serve. You can do this by returning multiple records in the same stored proc, combining multiple DB operations in same stored proc etc.

Use DataReader Instead of DataSet
Use DataReader objects instead of DataSet when ever you need to display data. DataReader is the most efficient means of data retrieval as they are read and forward only. DataSet are disconnected and in-memory therefore uses valuable server resources. Only use them when you need the same data more then once or want to do some processing on the data.

Last but certainly not the least follow the best coding, design and deployment patterns and practices. Here are few more usefull links that can be very helpful in performance optimization of you ASP.NET application
728x90

Apple에서 Windows 웹브라우저 시장에 뛰어 들었다. 과거 MAC에서 주로 사용해왔던 이 Safari라는 브라우저를 들고 Windows 플랫폼에서도 동작하게 만들어줬다. Apple 운영체제가 애시당초 그래픽 처리 하는 루틴에 많은 개선을 했기 때문에, Safari가 원래 빠르다고 생각했다. 그런데 Windows로 넘어와서도 그 속도를 그대로 유지하는 것에 놀랬다.

개인적인 체감속도로는 IE < FireFox < Safari 같다. 물론 Active X 안되는 거랑, 일부 우리나라 사이트에서는 일그러지는 현상이 발생되긴 하지만, 최소한 웹 표준 지킨 사이트라면 매우 훌륭하게 뿌린다. 그래서 실제 외국 사이트에서 정보를 보기 위해 접속할 때는 가급적 이 Safari를 애용한다.

그런데, 이상하게 Safari로 화면이 그려질 때, 한글이 묘하게 깨져서 나온다. 영어로 된 사이트에서는 큰 차이없이 잘 보이는데, 한글로 된 사이트에 들어가면 묘하게 한글의 일부분이 안보여서 그리다 만 것 같이 나오기도 한다.

좀 보기 좋으라고 한 기능인 것 같은데, 애석하게도 한글에서는 영 잘못 나온다.
아래의 그림이 그 일례다.



이 문제의 원인은 LCD 화면에 보다 잘 보이라고 Clear-Type 기법을 써서 그런 것 같다.
해결 하는 방법은 아래와 같다.

  1. Edit -> Preferences 에 들어간다.

  2. 옵션 항목들 중 Appearance에 들어가 Font Smoothings 항목에서 Medium - best for Flat Pannel 을 Standard - best for CRT 로 변경한다.

저장 버튼은 없으니까, 변경 후 닫기만 하면 된다.

728x90
예전에 Javascript 예제 소스를 받기위해 이곳 저곳을 들리다가, Javascript 안에서

  MOA.Service.Open("aaaaa", "12"."55");

식으로 소스를 적어놓은 것을 보았다.
처음에는 무슨 Object를 New 한뒤, 그 안의 메소드가 그렇게 된 줄 알았는데,
Javascript를 구성할 때, Namespace 기반으로 마치 Class 처럼 구현하는 방법으로
만들어 진 것이였다.
지금도 그렇지만 그 당시 나에게 Javascript는 넘지 못할 산이였고, Copy & Paste만 한채
더 이상 분석 없이 그냥 넘어 갔었다.

이번에 AJAX 기반의 WebPart를 만들면서 Javascript를 하나씩 사용하기 시작했는데,
그 때 보아왔던 Class 처럼 구현한 Javascript 의 원형을 보게 되었고, 그 구조를 뜯어보는
기회를 갖게되었다.


Javascript 에서 저런 "." 으로 구분된 형태로 구성하는 이유중에 하나는,
Namespace 때문이다.
예를 들어 함수나 변수 이름들을 넣을 때,  이름이 겹치지 않을까 하는 우려가 발생했다.
예를 들어 addNode 라는 함수를 만들었는데, 이 함수가 다른 Javascript에서도 사용하지
않을까... 라는 우려감이 그대로 드는 것이였다. 그럼 어떻게 해결 할까?

Javascript에서는 var 라는 변수 형에는 뭐든지 들어갈 수 있다는데 착안을 하여 구성한 것 같다.

즉 var AAA = { 'aaa', 'bbbb'  ,'cccc'  } 라는 배열을 넣듯이 그 안에 구성요소들을 때려
넣는 것이다. 이 때 name과 value라는 형태로 넣는데, 굳이 표현하면 아래와 같이 된다.

var AAA = { name : 'aaaa', tel : 'bbbbb' , addr : 'cccc' }

요소 1개는 name : 'aaaa' 이고, 2번째 요소는 tel : 'bbbbb' , 3번째 요소는 addr : 'cccc' 를 의미하게 된다. 만일 'aaaa' 라는 것을 접근하려면, AAA.name 으로 하면 'aaaa' 이 나오게 되는 것이다.

예를 들면 아래와 같이 클래스를 구성하게 된다.

var HelloClass = {
       variableA : null,
       RunIt: function (param) {
            this.variableA = param;
            alert(HelloClass .variableA);
       }
}

HelloClass.HelloMethod('OK!');

위의 자바 스크립트를 실행하면 'OK!' 라는 Alert 창이 뜬다.

잠시 위의 코드를 살펴보자.
보면, 이름과 그 형이나, 값을 ':' 으로 구분하여 구성한다.
보면 변수 부분은 변수이름을 variableA 로, 그 값은 null 로 규정했다.
그리고 함수 부분은 이름을 RunIt로, 그 값은 function(....) {....} 이라고 규정했다.

이렇게 만들면 저 맨위의 이름(예에서는 HelloClass )만 안겹치면 끝이다.

그리고, HelloClass를 접근할 때, HelloClass 자체를 써서 접근할 수 있고,
HelloClass 내부에서 접근할 땐 this라는 지시어를 써도 된다.

뭐 실제 class 처럼 proecteed, private 등의 접근 제어나 생성자 이런 부분이
명확치 않아서 의미가 별로 없긴 하지만, 네임 스페이스에 겹치지 않는 문제를
해결한다는 입장에서 볼때는 획기적인 방법이 아닐 수 없다.





728x90
정규식 표현(Regular Expressions) 작업은 다양한 텍스트 작업에 필수 이지만, 그 문법을 익히기엔 귀찮고 시간도 부족하고 특이한 형태를 뽑아내려면 많은 고민과 테스트를 해야 한다.
그렇다고 Window App로 만들어서 이런저런 테스트하기도 귀찮고..

그런 부분을 아는지 외국 사이트 중 이작업을 보다 수월하게 도와주는 곳이 있었다.

http://regexlib.com 

다행이 유료는 아니였다. 여러 난다 긴다는 분들이 자신만의 Expression들을 등록해 마치 라이브러리 처럼 유지되고 있었다. 일단 훌륭하게 운영되는 곳 같다.

게다가 이 사이트내에는 이 Expression을 테스트할 수 있는 도구도 제공한다.

http://regexlib.com/RETester.aspx

여기에 자신의 예제 텍스트들과 Expression을 넣고 돌리면 그 결과값을 볼 수 있다!!!
쵝오!
728x90

+ Recent posts

728x90