잊지 않겠습니다.

'ASP.NET MVC'에 해당되는 글 4건

  1. 2010.01.06 ASP .NET MVC RouteData Test Code
  2. 2009.12.27 ASP .NET MVC에서 Routing Test
  3. 2009.03.19 ASP .NET MVC Release.
  4. 2009.01.14 ASP .NET MVC에서 File Export
.NET Framework 4.0Beta2 로 작성된 application들은 NUnit에서 테스트가 불가능하다. NUnit는 .NET 2.x대의 base assembly만이 테스트가 가능하도록 작성되어 있기 때문이다.

그래서 MS의 xUnit test 를 이용해서 RouteData Test Code를 작성해보면 다음과 같다.
먼저, 가장 기본적인 RouteCollection을 생성하고, 테스트할 MVC application의 Route를 등록시킨다.
그리고 RouteCollection.GetRouteData(HttpBaseContext)를 이용해서 들어온 HttpBaseContext에 대한 RouteData를 확인한다.


[TestMethod]
public void TestMethod1()
{
    RouteCollection routeConfig = new RouteCollection();
    RouteApp.MvcApplication.RegisterRoutes(routeConfig);    
    RouteData routeData = routeConfig.GetRouteData(HttpBaseContext);
}


문제는 HttpBaseContext를 생성하는 것인데. Mock을 이용하면 간단하게 해결 할 수 있다.
다음 코드는 Mock을 이용해서 HttpBaseContext를 생성하는 코드이다.


private static Mock MakeMockHttpContext(string url)
{
    var mockHttpContext = new Mock();

    var mockRequest = new Mock();
    //HttpContext에 Request 설정
    mockHttpContext.Setup(x => x.Request).Returns(mockRequest.Object);
    //HttpRequest의 relative url로 사용자 지정 url 설정
    mockRequest.Setup(x => x.AppRelativeCurrentExecutionFilePath).Returns(url);

    var mockResponse = new Mock();
    //HttpContext에 Response 설정
    mockHttpContext.Setup(x => x.Response).Returns(mockResponse.Object);
    //HttpResponse에서 사용자 Url을 그냥 pass시키도록 ApplyAppPathModifier 수정
    mockResponse.Setup(x => x.ApplyAppPathModifier(It.IsAny())).Returns(x => x);            

    return mockHttpContext;
}


최종적으로 완성된 코드는 다음과 같다.

[TestMethod]
public void TestMethod1()
{
    RouteCollection routeConfig = new RouteCollection();
    RouteApp.MvcApplication.RegisterRoutes(routeConfig);

    var mockHttpContext = MakeMockHttpContext("~/");
    RouteData routeData = routeConfig.GetRouteData(mockHttpContext.Object);

    Assert.IsNotNull(routeData.Route);            
    Console.WriteLine(routeData.Values.ToString());
}
Posted by Y2K
,
Mockup class를 이용한 Routing test code
URL 테스트는 Rest 및 개발에서 가장 중요한 사항중 하나인데. 테스트코드보다 직접 실행해서 한번 테스트해보는 경우가 더 많은 것 같다.;



private string GetOutboundUrl(object routeValues)
{
    // Get route configuration and mock request context
    RouteCollection routes = new RouteCollection();
    MvcApplication.RegisterRoutes(routes);
    var mockHttpContext = new Moq.Mock();
    var mockRequest = new Moq.Mock();
    var fakeResponse = new FakeResponse();
    mockHttpContext.Setup(x => x.Request).Returns(mockRequest.Object);
    mockHttpContext.Setup(x => x.Response).Returns(fakeResponse);
    mockRequest.Setup(x => x.ApplicationPath).Returns("/");
    // Generate the outbound URL
    var ctx = new RequestContext(mockHttpContext.Object, new RouteData());
    return routes.GetVirtualPath(ctx, new RouteValueDictionary(routeValues)).VirtualPath;
}

이 code를 이용한 test code는 다음과 같이 적을 수 있다.
[Test]
public void Football_Page1_Is_At_Slash_Football()
{
    Assert.AreEqual("/Football", GetOutboundUrl(new
    {
        controller = "Product",
        action = "List",
        category = "Football",
        page = 1
    }));
}

URL의 테스트가 꼭 필요하긴 한데.. 요즘들어 일을 이런쪽으로 전혀 안하고 있다는 아쉬움이 많이 들고 있는듯.;
Posted by Y2K
,
일주일에 두번이상은 가는 asp.net 에서 배신을 당했다. ㅋㅋ 
18일날 대강 상황을 본 기억인데. 그날 바로 Release가 나오다니.;

일단 검토해본 결과 Release version과 RC1, RC2 버젼간의 차이는 Bug Fix 이외에는 발견하지 못했다. 

MS의 전통상... 
RC가 나오면 개발을 하더라도 변경이 아애 없는 경우가 많아서, RC 버젼이 나왔을때 대처하는 것이 좀더 나았던 경험들이 많은 것 같다. 

일단, 개발자들을 좀더 즐겁게 해줄 수 있는 ASP .NET MVC를 환영하고.. ^^
장고같은 REST service framework로도 발전할 수 있기를. ^^


Posted by Y2K
,
ActionResult의 Type중 ContentResult를 이용한다. 

먼저, Response 에 Buffer 설정과 Header 설정을 한다.
            Response.ClearContent();
            Response.AppendHeader("content-disposition", attachment);
            Response.Buffer = true;

다음 ContentResult의 결과를 넣어준다. 
<table>로 표현하는 경우에는 Excel에서 표로 읽는 것이 가능하다. 

            StringBuilder sb = new StringBuilder();
            sb.Append("<table>");
            sb.Append("<tr>");
            sb.Append("<td>Date</td>");
            sb.Append("<td>Comment</td>");
            sb.Append("</tr>");

            foreach(JoinOrLeaveReason joinOrLeaveReason in joinOrLeaveReasons)
            {
                sb.Append("<tr>");
                sb.AppendFormat("<td>{0:yyyy-MM-dd HH:mm:ss}</td>", joinOrLeaveReason.CreateDate);
                sb.AppendFormat("<td>{0}</td>", joinOrLeaveReason.Comment);
                sb.Append("</tr>");
            }
            sb.Append("</table>");

            ContentResult contentResult = new ContentResult();
            contentResult.ContentType = "application/wnd.ms-excel";
            contentResult.Content = sb.ToString();
            contentResult.ContentEncoding = Encoding.UTF8;

            return contentResult;

사용될 수 있는 Content-Type의 종류는 다음과 같다. 

1) Multipart Related MIME 타입
  - Content-Type : Multipart/related(기본형태)
  - Content-Type : Application/X-FixedRecord
  - Content-Type: Text/x-Okie; charset=iso-8859-1;

2) XML Media의 타입
 - Content-Type : text/xml
 - Content-Type : Application/xml
 - Content-Type : Application/xml-external-parsed-entity
 - Content-Type : Application/xml-dtd
 - Content-Type : Application/mathtml+xml
 - Content-Type : Application/xslt+xml

3) Application의 타입 
 - Content-Type : Application/EDI-X12:  Defined in RFC 1767 
 - Content-Type : Application/EDIFACT:  Defined in RFC 1767 
 - Content-Type : Application/javascript: Defined in RFC 4329 
 - Content-Type : Application/octet-stream: <-- 디폴트 미디어 타입은 운영체제 종종 실행파일, 다운로드를 의미
 - Content-Type : Application/ogg: Defined in RFC 3534 
 - Content-Type : Application/x-shockwave-flash: Adobe Flash files
 - Content-Type : Application/json: JavaScript Object Notation JSON; Defined in RFC 4627 
 - Content-Type : Application/x-www-form-urlencode <-- HTML Form 형태 

* x-www-form-urlencode와 multipart/form-data은 둘다 폼 형태이지만 x-www-form-urlencode은 대용량 바이너리 테이터를 전송하기에 비능률적이기 때문에 대부분 첨부파일은 multipart/form-data를 사용하게 된다. 

4) 오디오 타입
- Content-Type : Type audio: Audio 
- Content-Type : audio/mpeg: MP3 or other MPEG audio
- Content-Type : audio/x-ms-wma: Windows Media Audio;
- Content-Type : audio/vnd.rn-realaudio: RealAudio;  등등 
 

5) Multipart 타입(아카이브 또는 개체) 
- Content-Type : multipart/mixed: MIME E-mail; 
- Content-Type : multipart/alternative: MIME E-mail;
- Content-Type : multipart/related: MIME E-mail; Defined in RFC 2387 and used by MHTML(HTML mail) 
- Content-Type : multipart/formed-data : <-- 파일 첨부

6) TEXT 타입 
- Content-Type : text/css:  
- Content-Type : text/html:
- Content-Type : text/javascript 
- Content-Type : text/plain: 
- Content-Type : text/xml: 


7) 기타 MIMERPC 예제들 
가) HTTP with x/www-form-urlencoded 일반요청 
POST /some/resource HTTP/1.1
Content-type: application/x-www-form-urlencoded
0=example.getStateName&1=10023


[응답]
HTTP/1.1 200 OK
Content-type: text/plain
New York


나) HTTP x/www-form-urlencoded namedArgs getTeam
POST /some/resource HTTP/1.1
Content-type: application/x-www-form-urlencoded
0=example.getTeam&state=New York&sport=Baseball


[응답]
HTTP/1.1 200 OK
Content-type: multipart/mixed, boundary=B
--BYankees

--BMets

--B


다) HTTP x/www-form-urlencoded unicode addUser
POST /some/resource HTTP/1.1
Content-type: application/x-www-form-urlencoded
0=example.addUser&fname=Igna%ACio&lname=Sanchez


라) HTTP with multipart/form-data 요청
POST /some/resource HTTP/1.1
Content-type: multipart/form-data, boundary=AaB03x
--AaB03x
content-disposition: form-data; name="field1"


Joe Blow


--AaB03x  
content-disposition: form-data; name="pics"; filename="file1.gif"
Content-type: image/gif
Content-Transfer-Encoding: binary
...contents of file1.gif...


--AaB03x--

[응답] 
HTTP/1.0 200 OK
Content-type: text/plain
OK


마) Uploading multiple files with unicode

POST /foo HTTP/1.0
Content-type: multipart/form-data, boundary=AaB03x


--AaB03x
content-disposition: form-data; name="field1"
Joe Blow


--AaB03x  <-- 여러개의 파일을 첨부할 때 
content-disposition: form-data; name="pics"
Content-type: multipart/mixed, boundary=BbC04y

--BbC04y  <-- 첫번째 첨부파일은 텍스트
Content-disposition: attachment; filename="file1.txt"
Content-Type: text/plain; charset=UNICODE-1-1
Content-Transfer-Encoding: binary
... contents of some unicode file.txt ...


--BbC04y <-- 두번째 첨부파일은 이미지
Content-disposition: attachment; filename="file2.gif"
Content-type: image/gifContent-Transfer-Encoding: binary
...contents of file2.gif...

--BbC04y


----AaB03x--


바) XML and EMail 요청
HTP Request 
POST /x/foo/bar HTTP/1.0
reply-to-url: callback@domain.com
message-id: abc123
aynch: required0=getAuthorization&1="bobjones"


[응답] 
HTTP/1.0 200 OK
delivered-to: callback@domain.com
Content-length: 0
Mail/SMTP Response 
To: callback@domain.comFrom: mimeRPC@otherplace.com
in-reply-to: abc123
content-type: text/xml
<?xml version="1.0"?><this><is /><xml /></this>

Posted by Y2K
,