2010-12-12 6 views
23

MVX 용 C#에서 상당한 양의 ASPX 및 ASCX 파일이 있는데 새 Razor 구문으로 변환하고 싶습니다.Aspx to Razor 구문 변환기?

어떤 기관이이 작업을 더 빠르게 만드는 몇 가지 유틸리티를 알고 있습니까?

답변

26

나는 변환을 수행하는 작은 코드를 작성했습니다. 나는 그것이 다른 누군가에게 유용 할 수 있다고 생각한다. 나는 정규식의 balancing goup definitions에 관해 많은 것을 배웠다.

public static class RazorConversor 
{ 
    public static void ConvertAll(string directory) 
    { 
     string[] array = Directory.GetFiles(directory, "*.aspx", SearchOption.AllDirectories).Concat(
         Directory.GetFiles(directory, "*.ascx", SearchOption.AllDirectories)).ToArray(); 

     foreach (var fileName in array) 
     { 
      string aspxCode = File.ReadAllText(fileName); 
      string razorCode = ConvertToRazor(aspxCode); 
      File.WriteAllText(fileName, razorCode); //rename manually to update .csproj & source control 
     } 
    } 

    static readonly string[] DefaultNamespaces = new string[] 
    { 
     "System.Web.Helpers", 
     "System.Web.Mvc", 
     "System.Web.Mvc.Ajax", 
     "System.Web.Mvc.Html", 
     "System.Web.Routing", 
     "System.Web.WebPages", 
    }; 

    public static string ConvertToRazor(string aspxCode) 
    { 
     return ConvertToRazor(aspxCode, DefaultNamespaces); 
    } 

    public static string ConvertToRazor(string aspxCode, string[] defaultNamespaces) 
    { 
     //namespaces 
     string text2 = Regex.Replace(aspxCode, @"<%@\s+Import Namespace=""(?<ns>.*?)""\s+%>", 
      m => defaultNamespaces.Contains(m.Groups["ns"].Value) ? null : "@using " + m.Groups["ns"].Value); 

     //headers 
     string text3 = Regex.Replace(text2, @"<%@\s(?<dir>.*?)%>", m => "@{ " + m.Groups["dir"].Value + "}"); // Preserves headers 

     //expressions 
     string text4 = Regex.Replace(text3, @"<%[=:](?<expr>.*?)%>", m => 
     { 
      string expr = m.Groups["expr"].Value.Trim(); 
      string cleanExpr = Regex.Replace(expr, @"(""(\\""|[^""])*"")|(@""([^""]|"""")*"")|(\([^\(\)]*(((?'Open'\()[^\(\)]*)+((?'Close-Open'\))[^\(\)]*)+)*\))", m2 => ""); 
      return cleanExpr.Contains(' ') ? "@(" + expr + ")" : "@" + expr; 
     }, RegexOptions.Singleline); 

     //code blocks 
     string text5 = Regex.Replace(text4, @"<%(?<code>.*?)%>", m => 
     { 
      string code = m.Groups["code"].Value.Trim(); 

      Dictionary<string, string> stringLiterals = new Dictionary<string,string>(); 

      code = Regex.Replace(code, @"(""(\\""|[^""])*"")|(@""([^""]|"""")*"")", m2 => 
      { 
       string key = "<$" + stringLiterals.Count + "$>"; 
       stringLiterals.Add(key, m2.Value); 
       return key; 
      }); 

      string result = Regex.Replace(code, 
       @"((?<blockHeader>(else|(for|switch|foreach|using|while|if)\s*\([^\(\)]*(((?'Open'\()[^\(\)]*)+((?'Close-Open'\))[^\(\)]*)+)*\))\s*)" + 
       @"((?<fullBlock>{[^{}]*(((?'OpenCurly'{)[^{}]*)+((?'CloseCurly-OpenCurly'})[^{}]*)+)*})|(?<openblock>{.*))|" + 
       @"(?<text>((?!({|}|\s)(for|switch|foreach|using|while|if|else)(\s|{|\()).)+))", 
       m2 => 
       { 
        if(m2.Value.Trim().Length == 0 || m2.Value.StartsWith("else")|| m2.Value.StartsWith("}")) 
         return m2.Value; 

        if(m2.Groups["text"].Success) 
         return "@{ " + m2.Value.Trim() + "}\r\n"; 

        return "@" + m2.Value; 
       }, RegexOptions.ExplicitCapture | RegexOptions.Singleline); 

      result = Regex.Replace(result, @"<\$\d+\$>", 
       m2 => stringLiterals[m2.Value]); 

      return result; 
     }, RegexOptions.Singleline); 

     return text5; 
    } 
} 
+4

물론 프레드릭 룬트 (Fredrik Lundh)의 유명한 말을 들었을 것입니다. "어떤 사람들은 문제에 직면했을 때"나는 정규식을 사용할 것입니다. "라고 생각합니다. 이제 그들은 두 가지 문제가 있습니다." 유틸리티를 이용해 주셔서 감사합니다. –

+0

전 세계가 정규 표현식의 신축을 강조하는 도구를 기다리고 있다고 생각합니다. 잠시 동안 정규 표현식을 사용하지 않고 코드를 작성해야 할 필요가 있다고 생각합니다. – Olmo

+0

@Olmo : 나는 [RegExr] (http://gskinner.com/RegExr/)에 대해 좋은 경험을했습니다. 위젯을 가리키는 정규 표현식 부분을 강조 표시하고 상황에 맞는 도움말을 제공하기 때문에 좋습니다. 시도해보고 싶을 수도 있습니다. 데스크탑 버전도 제공합니다 (아직 사용하지는 않았습니다). – Oliver

1

Razor가 아직 베타 버전이 아니며 최신 SP에서 구문 강조 기능을 사용하고 있다는 점을 감안할 때 이러한 도구에는 너무 이른시기입니다. 바이너리 버전이없는, 따라서

이 프로젝트는 여전히 초기 단계에 있고 :

는하지만, 구글은 this CodePlex의 프로젝트를 찾습니다. 소스 코드를 다운로드 할 수 있습니다. VS2010을 컴파일해야합니다.

12

Telerik 여기에 변환 유틸리티를 출시했습니다 https://github.com/telerik/razor-converter

+0

Telerik의 소프트웨어에 대한 저의 경험은 상당히 무시 무시했습니다. 나는 원칙적으로 이것을 피하고 있습니다. Telerik aspx2razor +1 –

+2

+1 아름답게 일했습니다. 그것은 사용하기 쉬운 콘솔 exe입니다. Telerik은 수년 동안 훨씬 나아졌습니다. – GONeale

+0

@BenLesh 정말요? Telerik은 항상 나에게 꽤 좋았습니다. – BroVirus

1

을 시도해보십시오이

http://razorconverter.codeplex.com/

그것은 내가 그 일부 개선과 OLMA 코드를 자동으로 쓴 CodePlex의 프로젝트입니다. NET 2.0을 필요로하는 exe 다운로드도 있습니다. 당신이보기 폴더에 그것을 놓을 수 있고 자동으로 모든 것을 변환합니다.

+0

이것은 자주 분쇄되어 마스터 페이지를 지원하지 않는 telerik의 변환 유틸리티보다 나에게 잘 맞았습니다. –

+1

이 링크가 질문에 대답 할 수 있지만 여기에 답의 핵심 부분을 포함하고 참조 용 링크를 제공하는 것이 좋습니다. 링크 된 페이지가 변경되면 링크 전용 답변이 유효하지 않게 될 수 있습니다. - [리뷰에서] (리뷰/저품절 게시물/18785713) – rzelek