소스코드 문서화

 

개발자들은 개발 문서작업을 진행하는 데 많은 노력과 시간을 투자한다.

직접 모든 비즈니스 로직이나 모듈을 문서로 작성하기란 만만치 않은 작업이다.

MSDN형태의 도움말을 구독성이 뛰어나고 쉽게 구현하는 방법이 있어 이를 소개하고자 한다.

 

우선 소스코드 문서를 XML 파일로 바꿔주는 C#컴파일러의 기능에 대해 알아보자.

C# 컴파일러가 코드 주석을 XML로 변경하는 과정을 담당한다.

소스코드 주석 : /// , /** */

 

 XML 주석에서 사용하는 엘리먼트 정보들은 아래와 같다.

 

Element

정의

<c>

설명에 있는 텍스트를 코드로 표시하는 데 사용

<code>

여러 줄을 코드로 표시하는 데 사용

<example>

설명하고 있는 항목에 대한 코드 예제를 나타냄

<param>

파라미터를 설명한다

<remarks>

해당 멤버에 대한 설명을 작성하는 데 사용된다.

<returns>

멤버의 반환 값을 문서화한다.

<see>

관련된 항목들을 링크하는 데 사용한다.

<summary>

해당 항목에 대한 요약을 문서화 하는 데 사용한다.

<value>

해당 속성을 문서화하는데 사용한다.

[ 1]XML 주석 Element 설명

VS.NET 툴에서 기본적으로 IDE 기능들을 제공한다.

 

[
그림 1]VS.NET에서의 XML 주석

 

[그림 1]처럼 메소드 앞에 /// 3번 누르면 자동적으로 클래스나 메소드 및 필드에 맞는 element들이 생성되는 것을 볼 수 있다.

 

[
그림 2] VS.NET에서의 XML 주석


이것 외에 부연 설명이나 예제코드참고자료 등을 작성하고 싶을 경우에는 [그림 2]처럼 element를 추가하여 작성할 수 있다.

 

소스 코드에 네임스페이스클래스메소드나 멤버 변수에 XML 주석을 작성을 다 했으면 컴파일 시 /doc 옵션을 이용해 XML 문서를 추출해야 한다.

 

VS.NET 에서 프로젝트명 – 속성 – 빌드 탭에 XML문서 파일 설정을 체크하고 저장한다.

[
그림 3] VS.NET을 이용하여 XML 문서 출력

 

[그림 3]와 같이 설정한 후 컴파일을 하게 되면  bin\Debug\ePlayon.Batoo.BLL.XML 파일에 주석 문서가 생성된다.

아래 그림은 문서의 내용을 일부 발췌하였다.

 

[
그림 4] XML 문서 형식

 

파란색으로 표시된 내용을 보면 M:, T:와 같은 포맷 문자가 있다.

아래 [ 2]는 포맷 문자를 정리한 것이다.

 

Element

정의

N

네임스페이스

T

형식(클래스인터페이스구조체열거형델리게이트)

F

필드

P

형식 속성

M

메소드(생성자와 오버로드된 연산자 포함)

E

이벤트

!

에러에 대한 정보를 나타내는 에러 문자열

[표 2]XML 주석 포맷 문자

C# 컴파일러를 통해 생성된 이 xml 파일은 사용자 도움말 형태로 변환하기 위한 xml 정의 파일이라 할 수 있다.

그럼 사용자 도움말 형태로 만들기 위해 마이크로소프트에서 프리웨어로 제공하는 sandcastle 이라는 프로그램을 사용하여 작업을 진행해 보자.

Microsoft의 개발자들이 자신들이 도움말을 만들 때 사용하는 툴을 공개하였는데 그것이 바로 Sandcastle 이다.

Sandcastle 을 설치하기에 앞서 도움말 형태의 뷰어를 설치해야 한다.

아래 링크에서 HTML Help workshop  sandcastle, 그리고 sandcastle UI 프로그램을 다운받아 차례로 설치하자.

 

Microsoft HTML Help Downloads :

http://go.microsoft.com/fwlink/?linkid=14188

 

sandcastle Downloads:

http://www.codeplex.com/Sandcastle/Release/ProjectReleases.aspx?ReleaseId=9921

 

sandcastle help file builder Downloads :

http://www.codeplex.com/SHFB/Release/ProjectReleases.aspx?ReleaseId=9848

 

Sandcastle 원리

 

[
그림 5] Sandcastle 처리 원리

 

[그림 5] sandcastle이 내부적으로 소스코드를 문서화 해주는 과정을 나타내고 있다.

우선 VS.NET 툴에서 컴파일 시 XML 문서 파일을 출력하도록 하는 명령이 csc /doc 임을 알 수 있다컴파일이 성공하면 바이너리 폴더에 dll 파일과 xml 파일이 생성된다.

이때 SandCastle  BuildAssembler 에서 xml 파일과 dll 파일을 분석하여 필요한 정보들을 생성한 후 이 결과를 HTML Help Compiler에서 컴파일하여 도움말 형태로 출력시킨다.

 

그럼 sandcastle 툴을 사용하여 직접 소스 코드 도움말을 생성해보자.

앞서 봤듯이 dll 파일과 xml 파일은 있다는 가정 하에 테스트를 진행해 보겠다.

Sandcastle Help File Builder에서 “Sandcastle Help File Builder GUI” 를 실행시킨다.

 

[
그림 6] Sandcastle Help File Builder 메인 화면

 

[그림 6]은 Sandcastle의 기본 UI 이다. Add 버튼을 이용하여 바이너리(dll) 파일을 등록할 수 있다.

하지만 테스트할 바이너리는 웹 사이트의 모든 참조 라이브러리 프로젝트를 생성해야 하므로 수동으로 직접 입력하는 방법보다 솔루션 파일을 이용해 도움말을 생성해 보도록 하겠다.

 

[
그림 7] 솔루션 파일로 어셈블리 참조

 

[그림 7]에서 보듯이 Project 메뉴에 New Project from Visual Studio Project… 를 실행하여

솔루션 파일을 바인딩 시켜보자.

 

[
그림 8] 솔루션 파일로 바인딩 시 선택화면

 

솔루션 파일을 등록하게 되면 [그림 8]과 같이 나오면 Select 를 클릭한다.

 

[
그림 9] 솔루션 파일로 바인딩 시 UI

 

[그림 9]에서 보듯이 관련 참조된 어셈블리와 XML파일들이 바인딩 되는 것을 볼 수 있다.

이제 모든 준비가 끝이 났다.

 

우선 현재 sandcastle 프로그램을 저장하여 파일명.shfb파일을 도움말을 설치할 폴더에 저장한 후

Documentation 메뉴에 Build Project를 실행시켜보자.

 

[
그림 10] 도움말 생성 컴파일

 

[그림 10]의 아래 Output에서 보듯이 성공적으로 컴파일을 완료하였다.

저장한 폴더의 Help 폴더에 보면 Documentation.chm 파일이 생성된 것을 확인할 수 있다.

 

[그림 11] 도움말 생성 UI

 

[그림 11]에서 보듯이 성공적으로 도움말이 생성된 것을 확인하였다.


객체의 구조와 각 네임스페이스클래스메소드필드속성별로 설명이 되어 있다.


-출처 : http://tit99hds.egloos.com/1590155

'Programming > C#, ASP' 카테고리의 다른 글

Mono project  (0) 2015.04.22
Deployment Dependency Problems  (0) 2015.02.06
C# XML/XmlReader  (0) 2015.01.20
Troubleshooting Common Problems with the XmlSerializer  (0) 2015.01.20
ASP.NET Web API 도움말 페이지 작성하기  (0) 2015.01.15

C# 개발 툴 정하기

구글에 'free c# ide' 를 검색하니 사이트에 다양한 C# 개발 툴들이 있었다.

http://stackoverflow.com/questions/3640866/is-there-a-free-opensource-c-sharp-ide-in-windows

 

여러 개발 툴중에 평이하게 괜찮은 것은 비주얼 스튜디오 익스프레스이겠지만

크로스 플랫폼을 지원하는 툴을 사용하고 싶었다.

 

구글에 '리눅스 c#' 이라고 검색하니 나오는 것이 모노디벨롭이다.

모노디벨롭을 c# 개발 툴로 선정하였다.

 

 

 

 

 

모노 프로젝트 (C# .NET 크로스 플랫폼) 홈페이지

http://www.mono-project.com/

 

 

 

 

다운로드

http://monodevelop.com/

 

 

 

 

 

설치 파일

XamarinStudio-5.0.1.3-0.msi    38.4MB (40,300,544 바이트)

gtk-sharp-2.12.25.msi    24.5MB (25,690,112 바이트)

 

 

 

 

XamarinStudio-5.0.1.3-0.msi 를 설치하려 했는데

gtk-sharp-2.12.25.msi 를 먼저 설치하라고 한다.

 

 

 

 

설치 경로

홈 폴더 --

C:\CSharp\

 

gtk --

C:\CSharp\GtkSharp\2.12\

 

Xamarin Studio --

C:\CSharp\Xamarin Studio\    실패함

원래 위 장소에 설치하려 했는데 설치후 업데이트를 하면 설치장소가 기본 디렉터리로 변경된다.

C:\Program Files (x86)\Xamarin Studio\

 

워크스페이스 --

C:\CSharp\Projects\

 

설치파일 저장 --

C:\CSharp\util\

 

 

 

 

 

실행하기

C:\Program Files (x86)\Xamarin Studio\bin\XamarinStudio.exe

 

 

 

개발 툴 이름이 바뀌었다.

mono develop --> Xamarin Studio

 

별다른 설정없이 한글버전으로 설치되었다.


 - 출처 : http://blog.naver.com/lobolook/220185654654

'Programming > C#, ASP' 카테고리의 다른 글

.NET 소스코드 문서화  (0) 2015.07.13
Deployment Dependency Problems  (0) 2015.02.06
C# XML/XmlReader  (0) 2015.01.20
Troubleshooting Common Problems with the XmlSerializer  (0) 2015.01.20
ASP.NET Web API 도움말 페이지 작성하기  (0) 2015.01.15

Could not load file or assembly 'System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.IO.FileNotFoundException: Could not load file or assembly 'System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.


Assembly Load Trace: The following information can be helpful to determine why the assembly 'System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' could not be loaded.

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].


Stack Trace: 

[FileNotFoundException: Could not load file or assembly 'System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.]
   System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
   System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +210
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +242
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +17
   System.Reflection.Assembly.Load(String assemblyString) +35
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +122

[ConfigurationErrorsException: Could not load file or assembly 'System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.]
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +12534692
   System.Web.Configuration.AssemblyInfo.get_AssemblyInternal() +202
   System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +331
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +148
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +172
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +1151

[HttpException (0x80004005): Could not load file or assembly 'System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +12656404
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +159
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +12496021


API 프로그램을 서버 배포 시에 위와 같은 assembly loading이 안되는 문제가 발생 되었다.


문제는 컴파일시 해당 dll을 포함 시키면 되는 것이었다.


아는것이 힘. 경험도 힘 ^^


참조 : http://stackoverflow.com/questions/4742894/mvc3-deployment-dependency-problems



'Programming > C#, ASP' 카테고리의 다른 글

.NET 소스코드 문서화  (0) 2015.07.13
Mono project  (0) 2015.04.22
C# XML/XmlReader  (0) 2015.01.20
Troubleshooting Common Problems with the XmlSerializer  (0) 2015.01.20
ASP.NET Web API 도움말 페이지 작성하기  (0) 2015.01.15

Содержание

 [убрать]

Create XmlReader from Stream

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Xml;
using System.IO;
class MainClass
{
    static void Main(string[] args)
    {
        WebClient client = new WebClient();
        Stream rssFeedStream = client.OpenRead("http://yourRssFeedURL");
        XmlReader reader = XmlReader.Create(rssFeedStream);
        reader.MoveToContent();
        while (reader.ReadToFollowing("item"))
        {
            ProcessItem(reader.ReadSubtree());
        }
    }
    static void ProcessItem(XmlReader reader)
    {
        reader.ReadToFollowing("title");
        string title = reader.ReadElementContentAsString("title", reader.NamespaceURI);
        reader.ReadToFollowing("link");
        string link = reader.ReadElementContentAsString("link", reader.NamespaceURI);
        Console.WriteLine("{0}\n\t{1}", title, link);
    }
}

Read Xml output from database

using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using System.IO;
using System.Diagnostics;
    public class MainClass
    {
        public static void Main()
        {
            SqlConnection cnn = new SqlConnection(@"data source=.\sqlexpress;initial catalog=northwind;integrated security=true");
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = cnn;
            cmd.rumandType = CommandType.Text;
            cmd.rumandText = "select * from Employee FOR XML AUTO";
            cnn.Open();
            XmlReader reader=cmd.ExecuteXmlReader();
            StreamWriter writer= File.CreateText(Application.StartupPath + @"\temp.xml");
            writer.Write("");
            while (reader.Read())
            {
                writer.Write(reader.ReadOuterXml());
            }
            writer.Write("");
            writer.Close();
            reader.Close();
            cnn.Close();
            Process.Start(Application.StartupPath + @"\temp.xml");
        }
    }

Using XmlReader to read Xml result set from database

using System;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
public class DirectXML
{
    private static string connectionString = "Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI";
    public static void Main() 
    {
        string SQL = "SELECT CategoryID, CategoryName, Description FROM Categories FOR XML AUTO";
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand com = new SqlCommand(SQL, con);
        try
        {
            con.Open();
            XmlReader reader = com.ExecuteXmlReader();
            while (reader.Read())
            {
                Console.WriteLine(reader.Name);
                if (reader.HasAttributes)
                {
                    for (int i = 0; i < reader.AttributeCount; i++)
                    {
                        reader.MoveToAttribute(i);
                        Console.Write(reader.Name + ": " + reader.Value);
                    }
                    reader.MoveToElement();
                }
            }
            reader.Close();
        }
        catch (Exception err)
        {
            Console.WriteLine(err.ToString());
        }
        finally
        {
            con.Close();
        }
    }
}

XmlReader: ReadElementContentAsString

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Xml;
using System.IO;
class MainClass
{
    static void Main(string[] args)
    {
        WebClient client = new WebClient();
        Stream rssFeedStream = client.OpenRead("http://yourRssFeedURL");
        XmlReader reader = XmlReader.Create(rssFeedStream);
        reader.MoveToContent();
        while (reader.ReadToFollowing("item"))
        {
            ProcessItem(reader.ReadSubtree());
        }
    }
    static void ProcessItem(XmlReader reader)
    {
        reader.ReadToFollowing("title");
        string title = reader.ReadElementContentAsString("title", reader.NamespaceURI);
        reader.ReadToFollowing("link");
        string link = reader.ReadElementContentAsString("link", reader.NamespaceURI);
        Console.WriteLine("{0}\n\t{1}", title, link);
    }
}

XmlReaderSettings and XmlWriterSettings

using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
    public class MainClass
    {
        public static void Main()
        {
            XmlReader reader;
            XmlWriter writer;
            XmlReaderSettings readerSettings =new XmlReaderSettings();
            XmlWriterSettings writerSettings = new XmlWriterSettings();
            readerSettings.IgnoreComments = true;
            readerSettings.Schemas.Add(null, "pubs.xsd");
            readerSettings.ValidationType = ValidationType.None;
            writerSettings.OmitXmlDeclaration = true;
            writerSettings.Indent = true;
            writerSettings.NewLineOnAttributes = true;
            reader = XmlReader.Create("pubs.xml", readerSettings);
            writer = XmlWriter.Create("output.xml", writerSettings);
            while (reader.Read())
            {
                writer.WriteNode(reader, true);
            }
            reader.Close();
            writer.Close();
        }
    }

XmlTextReader in Action

using System;
using System.Xml;
  class XmlTextReaderSample {
    [STAThread]
    static void Main(string[] args) {
      XmlTextReader xmlTextReader = new XmlTextReader("sample.xml");
      while (xmlTextReader.Read()) {
        if (xmlTextReader.NodeType == XmlNodeType.Element) {
          Console.Out.WriteLine((new String(" ", xmlTextReader.Depth * 3)) + "Name: <" + xmlTextReader.Name +  ">; Depth: " + xmlTextReader.Depth.ToString() + "; Attributes count: " + xmlTextReader.AttributeCount.ToString() + ";");
        }
      }
    }
  }


XML serialize/deserialize를 하면서 생긴 문제에 대해 common한 trouble들을 설명하는 page

굉장히 도움이 되는듯 하다.

 

http://msdn.microsoft.com/en-us/library/aa302290.aspx

'Programming > C#, ASP' 카테고리의 다른 글

Mono project  (0) 2015.04.22
Deployment Dependency Problems  (0) 2015.02.06
C# XML/XmlReader  (0) 2015.01.20
ASP.NET Web API 도움말 페이지 작성하기  (0) 2015.01.15
프로젝트에 포함된 파일 access  (0) 2015.01.07
본 번역문서는 ASP.NET Web API 기술을 널리 알리고자 하는 개인적인 취지로 번역되어 제공되는 문서로, 원문을 비롯한 모든 저작권은 마이크로소프트사에 있습니다. 마이크로소프트사의 요청이 있을 경우, 언제라도 게시가 중단될 수 있습니다. 본 번역문서에는 오역이 포함되어 있을 수 있으며 주석도 번역자 개인의 견해일뿐입니다. 마이크로소프트사는 본 문서의 번역된 내용에 대해 일체의 보장을 하지 않습니다. 번역이 완료된 뒤에도 제품이 업그레이드 되거나 기능이 변경됨에 따라 원문도 변경되거나 보완되었을 수 있으므로 참고하시기 바랍니다.

Web API 개발 시, 다른 개발자들이 API의 사용법을 이해할 수 있도록 도움말 페이지를 함께 제공해주면 좋을 것입니다. 그리고, 이 도움말 페이지를 수작업으로 작성할 수도 있겠지만, 기왕이면 자동으로 생성하는 것이 더 편리할 것입니다.

ASP.NET Web API는 이런 작업들을 보다 손쉽게 처리할 수 있도록, 도움말 페이지를 런타임에 자동으로 생성할 수 있는 라이브러리를 제공해줍니다.



API 도움말 페이지 작성하기

먼저 ASP.NET and Web Tools 2012.2 Update 부터 설치해야 합니다. 이 업데이트는 Web API 프로젝트 템플릿에 도움말 페이지를 통합시켜 줍니다.

그런 다음, Web API 프로젝트 템플릿을 선택해서 새로운 ASP.NET MVC 4 프로젝트를 생성해보면, 프로젝트 템플릿에 의해서ValuesController라는 이름의 예제 API 컨트롤러가 생성될 것입니다. 이때, API 도움말 페이지도 함께 생성되는데, 참고로 도움말 페이지와 관련된 모든 코드 파일들은 프로젝트의 Areas 폴더에 위치합니다.

응용 프로그램을 실행시켜 보면, 홈 페이지에 API 도움말 페이지로 이동하는 링크가 추가되어 있는 것을 확인할 수 있습니다.

이 링크를 클릭하면 API 요약 페이지로 이동하게 됩니다.


이 도움말 페이지의 MVC 뷰는 Areas/HelpPage/Views/Help/Index.cshtml에 정의되어 있습니다. 따라서, 이 뷰 페이지를 수정하면 레이아웃이나 소개글, 제목, 형태 등을 원하는 대로 자유롭게 변경할 수 있습니다.

이 페이지의 핵심 부분은 API들의 표로, 컨트롤러를 기준으로 분류되어 있습니다. 그리고, 표의 각 항목들은 IApiExplorer 인터페이스를 통해서 동적으로 생성됩니다. (잠시 뒤에 이 인터페이스에 관해서 다시 살펴볼 것입니다.) 그래서, 새로운 API 컨트롤러가 추가되면 실시간으로 표가 갱신됩니다.

이 표의 "API" 컬럼에는 HTTP 메서드와 관련 URI들의 조합이 나타납니다. 그리고, "Description" 컬럼에는 각 API에 대한 설명이 제공되는데, 처음에는 아주 기초적인 내용들만 나타납니다. 다음 절에서는 XML 주석을 이용해서 이 설명을 편집하는 방법을 살펴볼 것입니다.

각 API 컬럼에는 요청 예제나 응답 본문 등을 비롯한 보다 자세한 정보들을 제공해주는 페이지로 이동할 수 있는 링크가 걸려 있습니다.

노트: NuGet 패키지 관리자를 이용해서 도움말 페이지를 추가할 수도 있습니다. 이 방법은 "Web API" 템플릿 대신 다른 프로젝트 템플릿을 통해서 프로젝트를 시작한 경우에 유용합니다. 도움말 페이지 패키지를 설치하려면, 패키지 관리자 콘솔에서 다음 명령을 실행합니다:
Install-Package Microsoft.AspNet.WebApi.HelpPage

API 문서 추가하기

기본적으로 도움말 페이지는 아주 기초적인 설명만을 제공해줍니다. 그러나, XML 문서 주석을 활용해서 이 설명을 편집할 수도 있습니다. 이 기능을 활성화하려면 Areas/HelpPage/HelpPageAreaRegistration.cs 파일을 열고 다음 줄의 주석을 제거하십시요:

config.SetDocumentationProvider(new XmlDocumentationProvider(
    HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));

그런 다음, 이번에는 XML 문서를 활성화시켜야 합니다. Visual Studio의 솔루션 탐색기에서 마우스 오른쪽 버튼으로 프로젝트를 클릭한 다음, 속성 (Properties)을 선택하고, 빌드 (Build) 페이지를 선택합니다.

계속해서 출력 (Output) 영역 하위의 XML 문서 파일 (XML documentation file) 항목을 체크한 다음, 그 우측의 입력 박스에 "App_Data/XmlDocument.xml"이라고 입력합니다.

그런 다음, /Controllers/ValuesControler.cs 파일에 정의되어 있는 ValuesController API 컨트롤러의 코드를 열고, 컨트롤러 메서드에 약간의 설명 주석을 추가합니다. 다음은 그 사례입니다:

/// <summary>
/// Gets some very important data from the server.
/// </summary>
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}
    
/// <summary>
/// Looks up some data by ID.
/// </summary>
/// <param name="id">The ID of the data.</param>
public string Get(int id)
{
    return "value";
}
: 캐럿을 메서드의 바로 위쪽 줄에 위치시킨 다음, 슬래시 문자를 세 개 입력하면 Visual Studio가 자동으로 XML 요소들을 삽입해줍니다. 그러면, 이 XML 요소들의 빈 칸을 채우기만 하면 됩니다.

이제 응용 프로그램을 다시 빌드하고 실행한 다음, 도움말 페이지로 이동해봅니다. 그러면, API 표에 주석에 입력한 내용들이 나타나는 것을 확인할 수 있습니다.

참고로 도움말 페이지는 런타임에 XML 파일로부터 문자열을 읽어들입니다. (따라서 응용 프로그램을 배포할 때, 이 XML 파일도 함께 배포해야만 합니다.)

내부 동작 방법

도움말 페이지는 Web API 프레임워크의 일부인 ApiExplorer 클래스를 기반으로 동작합니다. 이 ApiExplorer 클래스는 도움말 페이지를 생성하기 위한 기본적인 내용들을 제공해줍니다. ApiExplorer 클래스는 각 API들을 기술하는 ApiDescription 클래스들 갖고 있는데, 여기에서 말하는 "API"는 HTTP 메서드와 관련 URI의 조합으로 정의됩니다. 예를 들어서, 다음은 몇 가지 개별적인 API들의 목록입니다:

  • GET /api/Products
  • GET /api/Products/{id}
  • POST /api/Products

컨트롤러 액션이 복수의 HTTP 메서드들을 지원하는 경우, ApiExplorer 클래스는 각각의 HTTP 메서드들을 모두 별개의 API로 취급합니다.

그리고, 특정 API를 ApiExplorer 클래스로부터 감추려면 다음과 같이 ApiExplorerSettings 어트리뷰트를 액션에 추가하고 IgnoreApi 속성을 true로 설정하면 됩니다.

[ApiExplorerSettings(IgnoreApi=true)]
public HttpResponseMessage Get(int id) {  }

이 어트리뷰트는 컨트롤러에도 추가할 수 있으며, 그럴 경우 컨트롤러 전체가 숨겨집니다.

이 ApiExplorer 클래스는 IDocumentationProvider 인터페이스를 통해서 설명 문자열을 가져옵니다. 앞에서 살펴본 것처럼, 도움말 페이지 라이브러리는 XML 설명 문자열에서 설명을 가져오는 IDocumentationProvider 인터페이스를 제공해주며, 해당 코드는 /Areas/HelpPage/XmlDocumentationProvider.cs 파일에 존재합니다. 직접 IDocumentationProvider 인터페이스를 구현해서 다른 소스에서 설명을 가져올 수도 있는데, 이를 설정하려면 HelpPageConfigurationExtensions 클래스에 정의되어 있는SetDocumentationProvider 확장 메서드를 호출하면 됩니다.

ApiExplorer 클래스는 각 API들에 대한 설명 문자열을 얻기 위해서 자동으로 IDocumentationProvider 인터페이스를 호출합니다. 그리고, 이를 ApiDescription 개체와 ApiParameterDescription 개체의 Documentation 속성에 저장합니다.

다음 단계

본 자습서에서 살펴본 도움말 페이지 관련 내용에만 얽매일 필요는 없습니다. 애초에, ApiExplorer 클래스 자체가 도움말 페이지 생성 용도로만 사용하기 위한 것도 아닙니다. 이를테면, Yao Huang Lin은 사고의 틀을 깰 수 있게 해주는 몇 가지 멋진 블로그 포스트를 공개했습니다:


- 출처 : http://www.egocube.pe.kr/Translation/Content/asp-net-web-api/201308140001


'Programming > C#, ASP' 카테고리의 다른 글

Mono project  (0) 2015.04.22
Deployment Dependency Problems  (0) 2015.02.06
C# XML/XmlReader  (0) 2015.01.20
Troubleshooting Common Problems with the XmlSerializer  (0) 2015.01.20
프로젝트에 포함된 파일 access  (0) 2015.01.07

요즘 Restful API를 개발하면서 APICpntroller를 사용하여 개발하는 빈도가 높아졌다.

그래서 UI가 없는 단순 string 위주의 response가 많아지면서 내가 개발한 API를 사용하여 application를 개발하는 counter part의 개발자들에게 정해진 형식(json, xml)의 형태로 선개발을 진행 할 수 있도록 dummt data를 주는 프로그램을 만들면서 프로젝트에 포함된 파일을 access 하는 방법이 필요하게 되었다.


json으로 반환하는 data중에 xml row data를 반환하게 되어 있는데 하나의 xml이 굉장히 길었기 때문에 파일 io로 구현하기로 했는데 여러 방법을 시도해본 결과 다음과 같은 방법을 선택하였다.


먼저 환경은 asp.net MVC4이고 파일 경로는 프로젝트내 App_Data폴더에 추가 하였다.


public ReturnModel GetList()

        {

            item.Provider = 1;

            item.ResultList = new List<CommonResultModel>();


            string text = System.IO.File.ReadAllText(AppDomain.CurrentDomain.GetData("DataDirectory").ToString() + @"/1.xml", Encoding.Default);



            for (int i = 0; i < 20; i++)

            {

                CommonResultModel model = new CommonResultModel();

                model.GenreList = new List<string>();

                model.GenreList.Add("Politik & Weltgeschehen");

                model.GenreList.Add("Politik & Zeitgeschehen");

                model.ContentUrl = "http://83.125.32.32/hbbtv-ard/";

                model.Title = i + ". Franziskus' Kampf um Reformen geht in die heikle Phase";

                model.ThumbnailUrl = "http://83.125.32.35/hbbtv-ard/";

                model.Description = "Im Ringen um Reformen in der katholischen Kirche haben sich Tonfall und Gangart im Vatikan verschärft. In der Kurie und bei brennenden Fragen zu Ehe, Familie und Sexualmoral fehlen dem Papst eindeutige Mehrheiten. Gegner wittern Morgenluft. (Autor: Mike Lingenfelser)";

                model.Id = i;

                model.CreatedDate = String.Format("{0:yyyy-MM-dd}", new DateTime(2014, 12, 02));

                model.UpdatedDate = String.Format("{0:yyyy-MM-dd}", new DateTime(2014, 12, 02));

                model.Extends = text;


                item.ResultList.Add(model);

            }

            return item;

        }


중간에 AppDomain.CurrentDomain.GetData("DataDirectory").ToString() + @"/1.xml" 이 부분인데 "DataDirectory"라고 해도 App_Data폴더 주소가 나오는게 신기(?)했다.


-출처 : http://stackoverflow.com/questions/1268738/asp-net-mvc-find-absolute-path-to-the-app-data-folder-from-controller

'Programming > C#, ASP' 카테고리의 다른 글

Mono project  (0) 2015.04.22
Deployment Dependency Problems  (0) 2015.02.06
C# XML/XmlReader  (0) 2015.01.20
Troubleshooting Common Problems with the XmlSerializer  (0) 2015.01.20
ASP.NET Web API 도움말 페이지 작성하기  (0) 2015.01.15

+ Recent posts