'풀그림'에 해당되는 글 38건

  1. 2015.02.03 [펌] JTDS&Mabatis 에서 MSSQL NVARCHAR 처리 by 파이팅야
  2. 2014.02.05 git 관련 by 파이팅야
  3. 2013.11.26 lombok by 파이팅야
  4. 2011.07.07 HTML5 웹표준컴퍼런스2011 다녀와서 by 파이팅야 3
  5. 2011.01.20 C# HttpClient 에 대한 내용 by 파이팅야 2
  6. 2010.12.22 sql xml datatype 관련 by 파이팅야 4
  7. 2010.12.01 LogParser by 파이팅야 3
  8. 2010.04.14 uml class diagram relationship by 파이팅야
  9. 2009.07.23 CrouseControl .net 관련 by 파이팅야 2
  10. 2009.03.31 PowerShell로 svn 폴더 옮기기 by 파이팅야 2

MSSQL을 사용할 때
인덱스가 걸려있는 VARCHAR 컬럼데이터를 조회시 NVARCHAR로 데이터를 넘길경우
인덱스가 걸리지 않아 성능에 문제가 발생하는 사례가 존재한다.

(쿼리분석기에서는 빠른데 미들웨어에서 호출 시 느린경우)


 하여 보통은 jtds 드라이버 설정시
 sendStringParametersAsUnicode=false
 값을 주어 유니코드 처리하지 않게 함으로서 VARCHAR로 처리 되도록 하여 해결을 하고 있다.

 근데 문제는
 VARCHAR 와 NVARCHAR 가 섞여있을 경우에는 어떻게 해야 하는가?

 사실 이문제는 아래와 같이 풀면 해결이 될거라고 생각했다.

 1) 드라이버에서는 유니코드를 사용하지 않음 처리.
     - sendStringParametersAsUnicode=false
 2) mybatis mapper 에 jdbcType 을 부여
    - #{column, jdbcType=NVARCHAR}

 혹은 1)번을 부여하지 않고( default 는 sendStringParametersAsUnicode=true 이다. )
 #{column, jdbcType=NVARCHAR} 와 #{column, jdbcType=VARCHAR} 를 명시해주면 되지 않을까?

 라고 생각했었다.

 하지만, 결론은 안된다는거...

 그래서 jtds 드라이버 소스코드를 살펴 보았다.

 역시...NVARCHAR 사용을 위한 setNString() 에서 아래와 같은 코드로 구현이 되어있었고,

  [ JtdsCallableStatement.java ]

  public void setNString(String parameterName, String value)
            throws SQLException {
        // TODO Auto-generated method stub
        throw new AbstractMethodError();
    }

  public void setNString(int parameterIndex, String value)
            throws SQLException {
        // TODO Auto-generated method stub
        throw new AbstractMethodError();
    }

 실제 TdsData.java  ( getNativeType 메소드 ) , Support.java ( getJdbcTypeName 메소드 )내에서 지원가능한 jdbcType 검사를 하는데  여기에도 NVARCHAR 가 누락이 되어있다.

그럼 어떻게 NVARCHAR 를 지원하고 있었던걸까?

결론은 이렇다.

jtds 에서는 모든 NVARCHAR 든 VARCHAR 든 VARCHAR 로 인식하고 드라이버에 설정된 유니코드 사용여부에 따라 VARCHAR를 변환하고 있었던 것이다.

'모' 아니면 '도' 로 말이다.

그렇다면 이부분을 어떻게 해결할 수 있을까?

답은 간단하다.

setNString 구간에 setString 을 참조하여 내용을 체워주고,

JtdsPreparedStatement.java ]
protected void setParameter(int parameterIndex, Object x, int targetSqlType, int scale, int length)

메소드에 NVARCHAR 타입일 경우 pi.isUnicode = true 로 부여하면,

mybatis에서 NVARCHAR 로 jdbcType 을 부여한 것에 대해서 처리가 가능하다.

이때, mybatis 부분도 수정이 필요한데 이유는 이렇다.

mybatis 의 NVARCHAR 를 처리하는 NStringTypeHandler 라는 클래스가 존재하는데

이 클래스에서 파라미터 바인딩시 setString 이 호출되게 되어있다.

이걸 setNString 을 호출하게 변경하면, 정상처리가 되게 되는 것이다.


이번 기회에 jtds 내에서 어떤 일이 일어나는지 알게된 점이 좋았던거 같다.

그리고 왜 NVARCHAR 를 지원하지 않게 되어있는지...그리고 mybatis에서도 왜 NStringTypeHandler 에서도

setNString 이 아니라 setString 으로 되어있었는지에 대해서는 좀더 고민을 해봐야 할듯하다.

이유가 없지는 않을테니 말이다.

여하튼 이렇게 VARCHAR 와 NVARCHAR 을 Mix 에서 사용하는 곳에서는
이런 부분도 고려가 되어야 할듯하다.




출처 : http://ymseok.blogspot.kr/2013/07/jtds-mssql-nvarchar.html

Posted by 파이팅야
,

git 관련

풀그림 2014. 2. 5. 20:36
Posted by 파이팅야
,

lombok

풀그림 2013. 11. 26. 20:00


Lombok features overview

val
Finally! Hassle-free final local variables.
@NonNull
or: How I learned to stop worrying and love the NullPointerException.
@Cleanup
Automatic resource management: Call your close() methods safely with no hassle.
@Getter / @Setter
Never write public int getFoo() {return foo;} again.
@ToString
No need to start a debugger to see your fields: Just let lombok generate a toString for you!
@EqualsAndHashCode
Equality made easy: Generates hashCode and equals implementations from the fields of your object.
@NoArgsConstructor@RequiredArgsConstructor and @AllArgsConstructor
Constructors made to order: Generates constructors that take no arguments, one argument per final / non-null field, or one argument for every field.
@Data
All together now: A shortcut for @ToString@EqualsAndHashCode@Getter on all fields, and @Setter on all non-final fields, and@RequiredArgsConstructor!
@Value
Immutable classes made very easy.
@SneakyThrows
To boldly throw checked exceptions where no one has thrown them before!
@Synchronized
synchronized done right: Don't expose your locks.
@Getter(lazy=true)
Laziness is a virtue!
@Log
Captain's Log, stardate 24435.7: "What was that line again?"
@Delegate
Don't lose your composition.
experimental features
Here be dragons: Extra features which aren't quite ready for prime time yet.



References

1.     Lombok site : http://projectlombok.org/

2.     Lombok features : http://projectlombok.org/features/index.html

3.     Lombok annotion 설명 : http://jnb.ociweb.com/jnb/jnbJan2010.html

4.     Project Lombok - http://projectlombok.org

5.     Lombok API Documentation - http://projectlombok.org/api/index.html

6.     Project Lombok Issues List - http://code.google.com/p/projectlombok/issues/list

7.     Use Lombok via Maven - http://projectlombok.org/mavenrepo/index.html

8.     Project Lombok Google Group - http://groups.google.com/group/project-lombok

9.     Reviewing Project Lombok or the Right Way to Write a Library - http://www.cforcoding.com/2009/11/reviewing-project-lombok-or-right-way.html

10.   Morbok: Extensions for Lombok - http://code.google.com/p/morbok

11.   Using Project Lombok with JDeveloper - http://kingsfleet.blogspot.com/2009/09/project-lombok-interesting-bean.html


Posted by 파이팅야
,

1.     표준기술 적용 운영 사례

A.      오픈뱅킹(우리은행, 국민은행, 기업은행)

                         i.         Why IE – 인터넷 뱅킹이나 쇼핑몰등에서 ActiveX를 사용해서 IE의 점유율을 줄일 수는 없었다.

                        ii.         한국 인터넷 뱅킹 현황 - Active-X, (공인)인증서 서버인증서, 개인인증서, 암호화 교신,  금융 기관이 주는 보안 프로그램 (http://openweb.or.kr/?page_id=1028)

                       iii.         오픈뱅킹 우리은행에서 2010.7 월 국내 최초 서비스, OTP 사용으로 ActiveX-모듈 사용 배제(OTP를 타사의 눈치가 보여 그냥 주기는 그래서 이벤트에 참가하면 무료 증정하도록 함, 하나의 OTP로 타 은행에서도 사용 가능), 10만명 인터넷 뱅킹 신규 가입, 2,500명 신규 계좌 개설, 여수신 잔액 100억원 가량

                       iv.         우리은행 오픈뱅킹의 의미 (http://openweb.or.kr/?p=3059)

1.      화려함을 위해 플래시를 사용하지 않고 깔끔한 페이지 레이아웃,

2.      플러그인으로 암호화 하지 않고 웹페이지를 경량으로 구축 후  웹브라우저를 사용한 SSL 암호화를 사용하여 기존 플러그인을 사용하는 은행들 사이트보다 빠르다

3.      불필요한 보안 프로그램 제거 효과(방화벽, 바이러스, 키보드 보안[마우스로 클릭하게 만듬])

                        v.         지원 가능 OS/브라우저 리눅스에서 오페라 및 크롬이 조회서비스만 가능하고 나머지 OS(윈도우, 매킨토시) 및 브라우져(IE, 파폭, 사파리, 오페라, 크폼, 우분투, 페도라)에서 모두 사용 가능

                       vi.         국민은행 플러그인 방식의 개인방화벽 사용, PC 지정하면 보안카드 사용가능 하도록 해서 OTP카드 의무화를 배제 했다.

                      vii.         기업은행 – nProtect netizen에 대해서 강제 설치 함

                     viii.         인터넷뱅킹 보안 규정 구현 방식

1.      공인 인증서 - ActiveX에서 플로그인 방식으로 변경

2.      개인 방화벽 설치 플러그인, AciveX

3.      키보드 보안 가상 키보드

4.      웹페이지 보안 – (브라우저에서 제공하는)SSL 표준 프로토콜로 감독기관 승인

B.      iOSHTML5 관련App

                         i.         HTML5 Rederence Guide

                        ii.         HTML5 PRO

C.      HTML5로구현된참고사이트

                         i.         Channy'sBlog(http://channy.creation.net/blog/776 )

                        ii.         차세대웹표준HTML5의탄생과미래(http://www.skyventure.co.kr/insight/web/view.asp?Num=17119&NSLT=Y)

                       iii.         HTML5 Demos and Examples (http://html5demos.com/)

                       iv.         HTML5 그놈이온다(http://www.iamcorean.net/187)

                        v.         HTML5 Gallery(http://html5gallery.com)

                       vi.         HTML5 and the Future of the Mobile Web (http://www.slideshare.net/wonsuk73/html5-and-the-future-of-the-mobile-web)

                      vii.         HTML5 examples(http://www.phpguru.org/html5-examples#html5.canvas.examples)

                     viii.         15 HTML5 Demos Showcasing Prowess of HTML5 Over Adobe Flash(http://www.techdrivein.com/2010/08/15-html5-demos-showcasing-prowess-of.html)

2.     HTML5 적용 사례 소개

A.      HTML5 왜 필요한가?

                         i.         HTML4 + Applet + Flash è HTML5 + Canvas + Video + APIs (HTML5의 기능으로 모두 커버가 된다. 장치 비종속적이다. 범용적 웹 어플리케이션 표준)

                        ii.         사용자

1.      Geolocation API로 장치의 지리적 위치 정보를 활용하는 향상된 사용자 경험 제공

2.      Web Workers API를 이용한 JavaScript 멀티 쓰레드 지원으로 빠른 웹 환경 제공

                       iii.         개발자

1.      효율적인 사이트 구성, 향상된 사용자 경험 제공

                       iv.         마크업 개발에서의 HTML5

1.      <div class=”header”> è <header> 로 코드 자체로서의 의미 강화

B.      개발 표준

                         i.         구조(HTML)와 표현(CSS)으로 변경 전 후

1.      변경 전 – (HTML + CSS)<td bgcolor=“yellow”>첫번째 셀</td>

2.      변경 후 – (HTML) <td>첫번째 셀</td>, (CSS) td{backgroundcolor:yellow}

                        ii.         무엇이 좋아졌나?

1.      호환성 – IE, 파폭, Safari, Chrome, Opera(W7, Mac)

2.      개발 프로세스 단축 디자인(CSS)과 개발(HTML)이 동시에 진행될 수 있다.

3.      UI관려 유지보수 비용 감소 디자인 관련 문제는 CSS만 수정함

4.      코드 용량 감소 – '(1)Table è (2)Div + CSS è HTML5' 형태의 변화로 코드량이 감소한다.

C.      적용 사례

                         i.         개인화 웹

1.      변경 및 폐지된 Element, Attribute 초점

A.      의미가 변경된 Element

                                                    i.         <b>, <cite>, <hr>, <i>, <menu>, <s>, <small>, <strong>

B.      HTML5에서 사용할 수 없는 Element

                                                    i.         <basefont>, <big>, <center>, <font>, <s>, <strike>, <tt >, <u>, <frame>, <framesets>, <noframes>, <acronym>, <applet>, <isindex>, <dir>

2.      구조(HTML)와 표현(CSS)의 구분 확실 - Background, bgColor, border의 속성 사용할 수 없고 CSS(표현)으로만 사용할 수 있다.

                        ii.         모바일

1.      <Input type='search'> 사용해서 iphone 우측 하단에 'Search'버튼 보이도록 함

3.     웹에서의 실시간 네트워크 커뮤니케이션

A.      Google docs를 같은 웹페이지를 2개의 창에 띄우고 한곳에 수정하면 다른 곳도 싱크 맞추어짐 ç HTTP is connectionless

B.      HTML4에서의 방법

                         i.         Polling

1.      서버에 주기적으로 물어보는 방법(Comet 아님)

2.      네트웤 자원 낭비하고 요청 주기에 따라 사용자는 딜레이를 체감함

                        ii.         Long Polling (http://www.uengine.org:8088/wiki/index.php/Comet_%EA%B5%AC%ED%98%84_%EA%B8%B0%EB%B2%95)

1.      처음에 한번 서버에 요청하고 이후 서버에서 변경이 있을 시 Client에 응답이 오는 구조

2.      구현에 따라 서버에 부하가 있다.

                       iii.         Streaming

1.      HTTP chunked(Response Data가 커서 나누어서 Client로 전달함)는 구조

2.      IE에서는 onreadystate 3번으로 날라오지 않아서 iframe을 사용함. 따라서 딸깍 소리 들림

C.      제약사항

                         i.         브라우져 마다 가능 가능한 최대 커넥션 수(IE 2개의 컨넥션만 만들 수 있다고 함)

D.     HTML5에서의 방법

                         i.         ServerSentEvent

1.      Server에서 보내는 정보만 받을 수 있다.

2.      Client간의 통신은 안된다.

3.      지원 하는 브라우져가 많지 않다.(IE 9 이상도 미 지원)

                        ii.         WebSocket

1.      양방향 통신 지원

E.      적용 사례

                         i.         마이피플 – flash socket 사용함, 추후 HTML5 WebSocket 으로 변경 예정

                        ii.         Naver 야구 9주기적으로 결과를 받는 내용이 많으므로 Long Polling 적용함.

4.     HTML5 2D, 3D, 벡터 그래픽

A.      기존에는 Photoshop, Flash, Silverlight, CSS 등으로 '차트, 컨트롤(버튼)'등을 만들었지만 이젠 HTML5에서 다 가능하다.]

B.      2D in Canvas

                         i.         사용 예 (사각형 그리기)

1.      <canvas id="c1" width="150" height="150">

2.      var canvas = document.getElementById('tutorial');

3.      if (canvas.getContext){  var ctx = canvas.getContext('2d'); ctx.fillRect(25,25,100,100); }

                        ii.         paper.js (http://paperjs.org/)

C.      2D in SVG

                         i.         사용 예

1.      <body>

2.      <svg width="400" height="300">

3.      <text x="100" y="100"

4.      font-size=”50px”

5.      fill=”rgba(0,0,255,1)”

6.      stroke=”red” onclick="something();">

7.      Hello World!

8.      </text>

9.      </svg>

10.   </body>

                        ii.         일러스트레이터로 그리고 다른 이름 저장해서 SVG 내용 복사 후 붙여 넣으면 됨

                       iii.         Raphael JS 를 사용하면 HTML5 지원 가능하면 SVG를 사용하고 IE에서는 VML를 자동으로 사용하도록 함 (http://raphaeljs.com/)

D.     WebGL (3D)

                         i.         고려사항 명암, 거리, 원근, 제질

                        ii.         OpenGL ES 2.0 , GLSL(OpenGL Shading Language) ç SpiderGL, GLGE, C3DL, SceneJS

                       iii.         사용 예(http://bodybrowser.googlelabs.com)

5.     웹앱 및 하이브리드앱 개발

A.      Native Apps (iOS, android SDK로 개발되는 것)

                         i.         장점 - High Performance, Full Device Resource, App Store, Gaming Machine

                        ii.         단점 개발자 비용 큼, 배우가 어렵다, App Store에 접수하기 어렵고 오래 걸린다. Adroid의 경우 삼성이 만든 것과 다른 곳에서 만든 것이 서로 틀리다. Device가 너무 많다. 버전 관리는 해야 한다.

                       iii.         웹 앱으로 개발 가능한 것들도 있다 잡지, 앵그리버드, 트위터 등등이렇게 할려면 HTML5로 좋다.

B.      HTML5

                         i.         장점 - Open Web Standard, Multi Device, Multi Platform, Realtime Update 지원

                        ii.         단점 – Device Resource(카메라와 같은 장치를 사용하지 못함), Accessibility(인터넷이 되어야 사용가능), confidence, Cross-domain(cross domain에 접근 안됨), performance 떨어짐

C.      사용빈도

                         i.         www.Html5test.com 에서 조사한 내용에 따르면 HTML5 mobile용 브라우져(safari, webkit, chrome)등에서 많이 사용한다.

D.     하이브리드 앱

                         i.         Device Resource 가 사용 가능하다(Camera, Contact, GPS)

                        ii.         앱에서 Browser의 접근에 대한 confidence은 믿을 수 있게 된다.

                       iii.         App Store에서 복잡한 게임성 카테고리를(30%) 제외한 다른 카테고리들(70%)은 모두 앱으로 개발 가능하다.

E.      적용 방법

                         i.         WebApps to native Apps

1.      PhoneGap, Appspresso(Eclipse IDE)

                        ii.         Build Native Apps with web Technology

1.      Titanium 여러 Native App으로 만들어 주지만 개발언어가 어렵다.

                       iii.         WebApp NativeApp을 각각 개발하고 합친다.

6.     리얼타임 서비스 개발을 위한 자바스크립트 기술

A.      Javascript 개발 구조 관련

                         i.         소스보기가 가능하고 복사해서 갔다 쓸 수 있고, Validation 용으로 사용할 수도 있지만, Ajax + DHTML 등을 이용해서 한 페이지에서 여러 가지 처리를 하는 응용프로그램(Application)을 만들 수 있다.

                        ii.         그러나 JavaScript에서는 개발 구조 Framework이 없어서 개발하기 어려웠다. 그래서 MVC MVVM(ModelView ViewModel) 등이 나왔다. 일반적으로 AjaxController를 호출해서 결과 JSON을 받아서 화면에 출력한다고 할 때 출력 값에 태그(Design)과 내용(Data)이 함께 있어 분업해서 작업하기 힘들어 진다. 이런 것을 중간에 편하게 템플릿 기능을 하는 knockout.js 가 지원해 준다. JSON HTML을 자동으로 연동하게 해 준다.

B.      Realtime Service

                         i.         SNS, facebook, twitter, google+,

                        ii.         Javascript 엔진인 'Google v8'을 사용해서 chrome을 만들었다고 한다. 이후 'google v8' 을 가지고 서버 프로그램이 가능한 node.js를 만들었다.

                       iii.         Node.js 장점 – NIO, HTTP lib 포함, module system, Javascript

                       iv.         WebSocket

                        v.         NowJS - Client에서 호출한 Method Server에서 바로 사용할 수 있게 된다. 프로토콜을 공유한다. (http://dev.paran.com/2011/05/17/nowjs-nodejs/)

1.      Client – now.sendData(“abcd”);

2.      Server – everyone.now.sendData = function(data){ … }

C.      Mobile Javascript

                         i.         jqueryMobile, Sencha Touch 등이 있지만 많은 것을 수용하느랴 무겁다. 따라서 사용용도에 따라서 사용할 수 있는 다양한 Micro javascript Framework(FormfactorJS, MinPubSub, Modernizr, JSON2, Objs, OORJa, $script.js, Artemia, Augment.js, domReady …)를 사용하는 것이 좋다.



Google Docs에 있는 첨부파일들 참고하기



Posted by 파이팅야
,

HttpClient 의 설명 및 사용 예에 대해서 찾았으나 좋은 내용을 못찾다가 다음의 내용 찾음... REST 방식으로 Request / Response 해서 결과값 확인할 때 사용하면 좋을것 같음 (Unit Test 에도 사용하면 될것 같음)

Introduction

The WCF REST Starter Kit Preview 2 includes a set of classes designed to simplify interaction with REST web services. The communications are performed using theHttpClient class with the help of other types from the Microsoft.Http namespace. These types can be found in the Microsoft.Http.dll assembly located in theAssemblies folder of the starter kit.

Creating a HttpClient

There are three constructors to choose from. There is a default constructor and two others that allow you to set the base address of the web service you will be working with. The base address can be expressed as a String or Uri value.

1 HttpClient client1 = new HttpClient();
2 HttpClient client2 = new HttpClient("http://www.foo.com/");
3 HttpClient client3 = new HttpClient(new Uri("http://www.foo.com/"));

Sending a Message

The Send method of the HttpClient is used to begin a synchronous request. There are also extension methods available to help you configure your request for the different HTTP methods. We will cover those later as they actually use the Send method under the hood.

1 HttpClient client = new HttpClient("http://www.foo.com/");
2 HttpResponseMessage response = client.Send(HttpMethod.GET.ToString(), "RestService");

The Send method returns a HttpResponseMessage instance. You can use the response to check the response status code and retrieve any returned content. If you pass a URI into the Send method it will be added as a relative address to the base address.

Validating the Response

There are extension methods defined in the HttpMessageExtensions class that assist you in checking the returned status code. The HTTP status codes are defined in theHttpStatusCode enumeration in the System.Net namespace, which is part of the framework and not the starter kit.

When using the EnsureStatusIsSuccessful extension method an ArgumentOutOfRangeException is thrown if the status code is not HttpStatusCode.OK.

01 try
02 {
03     HttpClient client = new HttpClient("http://www.foo.com/");
04     HttpResponseMessage response = client.Send(HttpMethod.GET, "RestService");
05     response.EnsureStatusIsSuccessful();
06 }
07 catch (ArgumentOutOfRangeException exception)
08 {
09     Console.WriteLine(exception);
10 }

You can also use the EnsureStatusIs method to check for specific status codes. You must provide at least one status code to check. If the check fails anArgumentOutOfRangeException is thrown just the same as for the EnsureStatusIsSuccessful method.

1 HttpClient client = new HttpClient("http://www.foo.com/");
2 HttpResponseMessage response = client.Send(HttpMethod.GET, "RestService");
3 response.EnsureStatusIs(HttpStatusCode.PartialContent, HttpStatusCode.UnsupportedMediaType);

Send Extension Methods

As mentioned earlier, a number of extensions methods are defined in the HttpMethodExtensions class that help you configure your request with the appropriate HTTP method. There are extension methods for the GET, POST, PUT, DELETE and HEAD methods. The extension methods all end up calling the Send method of the HttpClientbeing extended with the appropriate HttpMethod value to indicate the HTTP method to use.

1 HttpClient client = new HttpClient("http://www.foo.com/");
2 HttpResponseMessage postResponse = client.Post("RestService", HttpContent.CreateEmpty());
3 HttpResponseMessage putResponse = client.Put("RestService", HttpContent.CreateEmpty());
4 HttpResponseMessage deleteResponse = client.Delete("RestService");
5 HttpResponseMessage headResponse = client.Head("RestService");

The Post and Put methods require you to provide the content that is to be sent to the server. Providing a null value for the HttpContent parameter will result in anArgumentNullException being thrown.

Sending Content

The Send method of the HttpClient class, along with the Post and Put extension methods, except a HttpContent instance to represent the content that should be sent to the web service. You create a new instance of the HttpContent class using its static Create method. An empty HttpContent instance can also be created using the staticCreateEmpty method. The Create method can be provided a wide range of parameters including string values, streams, byte arrays and ICreateHttpContent instances.

01 HttpClient client = new HttpClient("http://www.foo.com/");
02  
03 HttpContent stringContent = HttpContent.Create("Foo");
04 HttpResponseMessage response = client.Post("RestService", stringContent);
05  
06 byte[] bytes = Encoding.UTF8.GetBytes("Foo");
07 HttpContent byteContent = HttpContent.Create(bytes);
08 response = client.Post("RestService", byteContent);
09  
10 using (MemoryStream memoryStream = new MemoryStream(bytes))
11 {
12     HttpContent streamContent = HttpContent.Create(memoryStream);
13     response = client.Post("RestService", streamContent);
14 }

The HttpMultipartMimeForm and HttpUrlEcodedForm classes are examples of classes that implement the ICreateHttpContent interface. These are helper classes that build up the HttpContent instances in more advanced scenarios.

Receiving Content

The content for a response is accessible via the Content property of the HttpResponseMessage. Like the content sent in the request, the property is of type HttpContent. The HttpContent class contains some helper methods for retrieving the data it contains. These include ReadAsByteArrayReadAsStream and ReadAsString. They return the content in the format that their names suggest.

1 HttpClient client = new HttpClient("http://www.foo.com/");
2 HttpResponseMessage response = client.Get("RestService");
3  
4 byte[] byteArrayContent = response.Content.ReadAsByteArray();
5 Stream streamContent = response.Content.ReadAsStream();
6 string stringContent = response.Content.ReadAsString();

Using Headers

HTTP headers play an important role in REST web services. The RequestHeaders class represents the headers that are sent in the request, and the ResponseHeaders class represents the headers returned in the response. Both of these classes derive from the HttpHeaders class. This base class acts like a dictionary for the headers and exposes properties to access the most common header values.

The static Parse method on the RequestHeaders class can take a string of headers and extract the values. It assumes that the headers appear on separate lines.

1 const string headers = "Content-Type: text/xml\r\nReferer: http://www.referer.com";
2 RequestHeaders requestHeaders = RequestHeaders.Parse(headers);

You can also use the properties to set the header values individually, and in a more strongly-typed manner.

1 RequestHeaders requestHeaders = new RequestHeaders
2 {
3     ContentType = "text/xml", Referer = new Uri("http://www.referer.com")
4 };

The response headers are accessed via the Headers property of the HttpResponseMessage instance returned from the Send method of the HttpClient, or from one of the extension methods found in the HttpMethodExtensions class.

1 HttpClient client = new HttpClient("http://www.foo.com/");
2 HttpResponseMessage response = client.Get("RestService");
3 Console.WriteLine(response.Headers.ContentType);

Sending Asynchronously

There are two ways of sending a request asynchronously via the HttpClient. The first is to call the BeginSend method and provide an AsyncCallback delegate. The second is to call the SendAsync method and subscribe to the SendCompleted event. You must prepare a HttpRequestMessage instance to provide to both of these methods as they do not provide the same overloads as the Send method.

The BeginSend method uses the typical IAsyncResult pattern. This allows you to continue with other work and have the callback delegate invoked, or wait for the result using a wait handle or through polling. The example below continues execution leaving the AsyncCallback delegate to be invoked when the request has completed. TheEndSend method on HttpClient is called with the IAsyncResult provided to the callback to get access to the response message.

1 HttpClient client = new HttpClient("http://www.foo.com/");
2 HttpRequestMessage request = new HttpRequestMessage(HttpMethod.GET.ToString(), "RestService");
3 AsyncCallback callback = asyncResult =>
4      {
5          HttpResponseMessage response = client.EndSend(asyncResult);
6          Console.WriteLine(response.StatusCode);
7      };
8 client.BeginSend(request, callback, null);

The SendAsync method allows you to send requests asynchronously and be informed when a request has completed via the SendCompleted event. The event argument is of type SendCompletedEventArgs and exposes Request and Response properties. As expected, these properties provide access to the original HttpRequestMessage, and the returned HttpResponseMessage. There is also a UserState property, which is actually defined on the base SendCompletedEventArgs, that can be used to return an object that was passed into the SendAsync method. The user state can be used as a key of sorts to match up returning responses with the requests that initiated them.

1 HttpClient client = new HttpClient("http://www.foo.com/");
2 HttpRequestMessage request = new HttpRequestMessage(HttpMethod.GET.ToString(), "RestService");
3 client.SendCompleted += (s, e) => Console.WriteLine(e.UserState);
4 const string userState = "foo";
5 client.SendAsync(request, userState);

Summary

The HttpClient provides a simple and clean API for working with REST web services. It removes a great deal of the complexity that is inherent with working so close to the HTTP stack. All the HTTP methods are supported, including the common GET, POST, PUT and DELETE methods. Building content for your requests and extracting content from responses has been greatly simplified. The common HTTP headers for the request and response can be accessed through a strongly-typed interface. You can check the status of responses without having to worry about remembering the numeric HTTP status codes. There are two different patterns available for performing asynchronous requests.


출처 : http://alexmg.com/post/2009/04/07/Introduction-to-the-HttpClient.aspx

Posted by 파이팅야
,

sql xml datatype 관련

풀그림 2010. 12. 22. 15:23

l  개요

n  xml 데이터 형식을 사용하면 XML 문서와 조각을 SQL Server 데이터베이스에 저장할  있습니다xml 유형의열과 변수를 만들어 데이터베이스에 XML 인스턴스를 저장할  있습니다저장된 xml 데이터 형식 인스턴스 표현은 2GB 초과할  없습니다.

n  선택적으로 XML 스키마 컬렉션을 xml 데이터 형식의 매개 변수 또는 변수와 연결할  있습니다컬렉션의스키마는 XML 인스턴스의 유효성을 검사하고  인스턴스를 형식화하는  사용됩니다 경우 XML 형식화되었다고 합니다.

l  Xml 데이터 유형 메서드

n  Query() -  XML 인스턴스(Nodes) 대해 쿼리합니다

u 

 declare @myDoc xml

 set @myDoc = '<Root>

 <ProductDescription ProductID="1" ProductName="Road Bike">

 <Features>

 <Warranty>1 year parts and labor</Warranty>

 <Maintenance>3 year parts and labor extended maintenance is available</Maintenance>

 </Features>

 </ProductDescription>

 </Root>'

 SELECT @myDoc.query('/Root/ProductDescription/Features')

u  결과

 <Features>

 <Warranty>1 year parts and labor</Warranty>

 <Maintenance>3 year parts and labor extended maintenance is available</Maintenance>

 </Features>

n  Value()- XML 인스턴스에서 SQL 유형의 값을 검색합니다

u 

n  value() 사용예첫번째productID attribute의값검색해서prodID 변수에셑팅함

 DECLARE @myDoc xml

 DECLARE @ProdID int

 SET @myDoc = '<Root>

 <ProductDescription ProductID="2" ProductName="Road Bike1">

 <Features>

 <Warranty>1 year parts and labor1</Warranty>

 <Maintenance>3 year parts and labor extended maintenance is available1</Maintenance>

 </Features>

 </ProductDescription>

 </Root>'

 

 SET @ProdID =  @myDoc.value('(/Root/ProductDescription/@ProductID)[1]', 'int' )

 SELECT @ProdID

u  결과

 2

n  Exists() -  쿼리에서 비어 있지 않은 결과를 반환하는지 여부를 확인합니다.

u 

 declare @x xml

 declare @f bit

 set @x = '<root Somedate = "2002-01-01Z"/>'

 set @f = @x.exist('/root[(@Somedate cast as xs:date?) eq xs:date("2002-01-01Z")]')

 select @f

u  결과

 1

n  Modify() -  업데이트를 수행하도록 XML DML 문을 지정합니다. (XML 데이터에서 노드를 삽입업데이트 또는삭제합니다)

u 

 DECLARE @myDoc xml      

 SET @myDoc = '<Root>      

 <ProductDescription ProductID="1" ProductName="Road Bike">      

 <Features>      

 </Features>      

 </ProductDescription>      

 </Root>'      

 SELECT @myDoc      

n  insert first feature child (no need to specify as first or as last)      

 SET @myDoc.modify('      

 insert <Maintenance>3 year parts and labor extended maintenance is available</Maintenance>

 into (/Root/ProductDescription/Features)[1]')

 SELECT @myDoc

u  결과

 <Root>

 <ProductDescription ProductID="1" ProductName="Road Bike">

 <Features>

 <Maintenance>3 year parts and labor extended maintenance is available</Maintenance>

 </Features>

 </ProductDescription>

 </Root>

n  Nodes() -  XML 여러 행으로 나누어 XML 문서 부분을  집합으로 전파합니다

u 

 DECLARE @x xml

 SET @x='<Root>

 <row id="1"><name>Larry</name><oflw>some text</oflw></row>

 <row id="2"><name>moe</name></row>

 <row id="3" />

 </Root>'

 

 SELECT T.c.query('.') AS result

 FROM   @x.nodes('/Root/row') T(c)

u  결과

 <row id="1"><name>Larry</name><oflw>some text</oflw></row>

 <row id="2"><name>moe</name></row>

 <row id="3" />

l  XML Data Model 이 필요한 경우

n  데이터가 산발적이거나 데이터 구조를 알 수 없거나 데이터 구조가 이후에 크게 변경될 수 있습니다.

n  데이터가 엔터티 간 참조 대신 포함 계층을 나타내며 재귀적일 수 있습니다.

n  데이터에 정렬이 내재되어 있습니다.

n  데이터 구조를 기반으로 데이터를 쿼리하거나 데이터 일부를 업데이트하고자 합니다.

l  장점

n  Xml column에 데이터를 저장하면 엔진에서 테이터가 잘 작성되었거나 유효한지 여부를 확인할 수 있습니다.

n  XML 데이터의 세부적 쿼리 및 업데이트가 지원됩니다.

n  해당 xml 데이터를 여러 곳에서 공유해서 사용가능 하다.

n  XML 쿼리 성능의 속도를 높이기 위해 XML 데이터를 인덱싱할  있습니다인덱싱 옵션은 스토리지 옵션별로 다르므로 작업을 최적화할  있는 적합한 옵션을 선택해야 합니다

l  단점

n  XML column 을 사용하는 쪽에서 xml 조작하는 쿼리를 이해하고 있어야 한다.

n  SQL 2005 부터 지원하므로 SQL 2000에서는 사용할 수 없다.

l  참고

n  성능상의 이슈로 where 조건에는 exist()를 사용하도록 하는 것이 좋음

n  SQL 2000 SQL 2005에서의 XML Data Update 작업을 비교한 내용

u  http://redju.blogspot.com/2006/05/sql-server-2005-xml-1.html

l  개인적인 생각으론 데이터가 산발적이거나 데이터 구조를 알 수없을 때 사용하면 좋을것 같다.

l  물론 XML에 저장된 값으로 검색이 필요하지 않으면 사용하기 더 좋을듯. XML 유효성 체크도 해줘서 좋구 

l  XML 저장된 값을 검색할려면  인덱싱 해야 하고, 인덱싱 할려면 정해진 XML 형식(Typed XML)이어야 한다. XML 형식이 각각 다른 경우(Untyped XML)에는 인덱싱이 안 되어 느림

l  참고 URL : http://msdn.microsoft.com/en-us/library/ms345117(v=sql.90).aspx

 

Posted by 파이팅야
,

LogParser

풀그림 2010. 12. 1. 20:26

Posted by 파이팅야
,

1.     Generalization

2.     Implementation

3.     Association

A.     class변수 사용하는 경우

B.      A class에서 B class association 관계인 예

public class A{

B b = null;

}

4.     Dependency

A.     Method 인자로 type을 받아서 처리하는 경우

B.      A class에서 B class Dependency 관계인 예

Public class A{

setB(B b){

b.printName();

}

}

5.     Composition

A.  집합이고 연관된 class들의 Lifecycle이 같은 경우

B.  A class에서 B class composition 관계인 예

C. 강한열결이여서 다이아몬드가 채워져있는 모양으로 Collection을 가진쪽이 다이아몬드가 있는 쪽임

C.      

public class A{

ArrayList<B> b;

public A(){

this.b = new ArrayList<b>(100);

}

}

6.     Aggregation

A.     집합이고 연관된 class들의 Lifecycle이 다른 경우

B.      A class에서 B class Aggregation 관계인 예

public class A{

ArrayList<B> b;

setB(ArrayList<B> b1){

this.b = b1;

}

}

Posted by 파이팅야
,

빌드서버 구축시 참고내용

·     64비트용으로 만든 프로젝트의 unit test를 실행하기 위해 빌드서버는 64비트 OS여야 함

·     설치해야 하는 프로그램들

o    svn.exe파일이 path에 잡혀있어야 함(visualSVN Server설치하고 visualSVN서비스는 시작하지않음)

o    VS 6.0, VS.NET 2003, VS.NET 2005 순서대로 설치해야 하며 VS.NET 2005 설치시(x64빌드 도구 선택해서 같이 설치해야 64비트용 프로젝트 빌드됨)

o    java jdk, ant 설치하고 JAVA_HOME, ANT_HOME등을 환경변수에 지정하고 path도 잡아야 함, Ant의 빌드결과를 CC.NET에서 확인할려면 dashboard.config xslReportBuildPlugin값 넣어야 함(자세한것은 CC.NET문서 참고)

o    NUnit, NAnt, TortoiseSVN, IIS, SMTP서버, SQL Client, Window Powershell(윈도우용 shell 프로그램)


개발 시 참고내용

·     솔루션이나 프로젝트 파일의 참조 라이브러리 위치는 상대경로여야 한다.(메모장으로 .proj 파일 열어서 hintpath부분 확인)

·     참조하는 로컬폴더의 위치는 모두 동일해야 한다.(ex> d:\commonLib\Base …)


Ccnet.config

<project name="IPMSC2" queue="PROJ">

    <triggers>

      <scheduleTrigger time="03:00" buildCondition="ForceBuild" name="Scheduled" />

    </triggers>

    <webURL>http://70.70.70.26:4989/server/local/project/IPMSC2/ViewProjectReport.aspx</webURL>

    <labeller type="dateLabeller" />

    <sourcecontrol type="svn">

      <trunkUrl>http://x.dev:8080/svn/IPMSCv2.root/IPMSC</trunkUrl>

      <workingDirectory>D:\CruiseControlBuild\IPMSC2</workingDirectory>

      <autoGetSource>true</autoGetSource>

      <cleanCopy>true</cleanCopy>

    </sourcecontrol>

    <tasks>

      <devenv>

        <solutionfile>D:\CruiseControlBuild\IPMSC2\IPMSC.sln</solutionfile>

        <configuration>Release</configuration>

        <buildtype>ReBuild</buildtype>

        <version>VS2005</version>

        <buildTimeoutSeconds>1200</buildTimeoutSeconds>

      </devenv>

      <buildpublisher>

        <sourceDir>D:\CruiseControlBuild\IPMSC2\IPMSC_Console\bin\Release</sourceDir>

        <publishDir>D:\CruiseControlRelease\IPMSC2</publishDir>

        <useLabelSubDirectory>true</useLabelSubDirectory>

        <alwaysPublish>false</alwaysPublish>

</buildpublisher>

      <nant>

        <executable>nant.bat</executable>

        <baseDirectory>D:\CruiseControlRelease</baseDirectory>

        <nologo>true</nologo>

        <buildFile>makeZipFile.build</buildFile>

      </nant>

    </tasks>

</project>

 

NAnt 파일 makeZipFile.build

<?xml version="1.0" encoding="utf-8"?>

<project name="Zip Example" default="makeZip">

  <target name="makeZip">

    <echo message="## CCNetLabel[${CCNetLabel}]" />

    <echo message="## CCNetProject[${CCNetProject}]" />

<zip zipfile="D:\CruiseControlRelease\${CCNetProject}\${CCNetLabel}\${CCNetProject}.${CCNetLabel}.zip">

      <fileset basedir="D:\CruiseControlRelease\${CCNetProject}\${CCNetLabel}" defaultexcludes="true" failonempty="true">

        <include name="**/*" />

      </fileset>

    </zip>

<delete>

      <fileset basedir="D:\CruiseControlRelease\${CCNetProject}\${CCNetLabel}" defaultexcludes="false">

        <include name="**/*" />

        <exclude name="${CCNetProject}.${CCNetLabel}.zip" />

      </fileset>

    </delete>

</target>

</project>

관련 URL
http://confluence.public.thoughtworks.org/display/CCNET/Welcome+to+CruiseControl.NET


이용 사례 정리한 것 (20110304)

Posted by 파이팅야
,

만약

             game/source/app

             game/source/app/file.txt

             game/source/app/subfolder

와 같이 있는 파일 및 폴더를

             game/source/trunk

안에 옮기고자 할려면

 

일단 아래와 같은

svn move game/source/app game/source/trunk

move명령어는 같은 폴더라 실행은 안되고

 

app폴더를 임의 temp폴더로 복사하고 app폴더를 삭제 후

trunk, branches, tags폴더를 만들고 trunk폴더안에 temp폴더의 내용을 옮겨야 합니다.

 

그리고 파일을 app폴더에서 temp폴더로 옮길 때 *(wildcards)가 실행되지 않아서

Linux면 아래의 URL처럼 shell script로 되는데…

(http://subversion.tigris.org/faq.html#sorry-no-globbing)

 윈도우면 PowerShell로 구현하면 될것 같음

 .Net Framework 2.0설치하고 PowerShell을 설치 후 아래의 내용으로 moveFolder.ps1파일을 만들어 실행하면 됨

 

# 옮길 SVN URL값을 읽어들임

$moveList = Get-Content d:\temp\moveList.txt

foreach($moveFile in $moveList)

{

             $url = "http://pccafe2.ncsoft.dev:8080/svn/" + $moveFile

             echo "URL[$url]"

 

             # URL의 마지막 폴더명 구하기

             $splittedUrl = $moveFile.split("/")

             $lastFolder = $splittedUrl[$splittedUrl.length - 1]

 

             svn ls "$url" > "FILE_LIST_$lastFolder.xml"

             $fileList = Get-Content "FILE_LIST_$lastFolder.xml"

             foreach($file in $fileList)

             {

                           # URI형식으로 주소값 변경(변경하지 않으면 한글이나 띄어쓰기 있는부분에서 에러남)

                           $sourceUri = [System.URI] "$url/$file"

                           $targetUri = [System.URI] "http://pccafe2.ncsoft.dev:8080/svn/game/backup/$lastFolder/$file"

 

                           # 파일 복사

                           svn copy --parents $sourceUri.AbsoluteUri $targetUri.AbsoluteUri -m "copy backup"

             }

}

옮기는경우가 많지 않으면, TortoiseSVN에서 마우스 오른쪽 버튼으로 드래그한후 move메뉴를 실행하면 된다.

ㅇ. 참고
http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx

Posted by 파이팅야
,