2010-06-03 36 views
1

我在當前項目中使用CodeSmith,並試圖找出問題。對於我的CodeSmith項目(.csp),我可以選擇一個選項讓它自動將所有生成的文件添加到當前項目(.csproj)。但我想能夠將輸出添加到多個項目(.csproj)。 CodeSmith裏面有一個選項來允許這個嗎?或者有沒有一種編程方式的好方法?如何使用CodeSmith工具將生成的文件添加到多個項目

謝謝。

回答

2

我無法想出讓CodeSmith自動處理這個問題的方法,所以我最終在Code Behind文件中編寫了一個自定義方法來處理這個問題。

一些注意事項: - proj文件是XML,因此編輯起來相當容易,但實際上包含在項目中的文件列表的「ItemGroup」節點實際上沒有標記特殊的方式。我最終選擇了「包含」子節點的「ItemGroup」節點,但是可能有更好的方法來確定您應該使用哪個節點。 - 我建議一次完成所有proj文件的更改,而不是創建/更新每個文件。否則,如果你從Visual Studio啓動代,你可能會得到大量的「這個項目已經改變,你想重新加載」 - 如果你的文件是在源代碼控制下(他們是,對嗎?!),你要去需要處理檢查文件並將它們添加到源代碼控制中,同時編輯proj文件。

這裏是(或多或少)我用一個文件添加到項目中的代碼:

/// <summary> 
/// Adds the given file to the indicated project 
/// </summary> 
/// <param name="project">The path of the proj file</param> 
/// <param name="projectSubDir">The subdirectory of the project that the 
/// file is located in, otherwise an empty string if it is at the project root</param> 
/// <param name="file">The name of the file to be added to the project</param> 
/// <param name="parent">The name of the parent to group the file to, an 
/// empty string if there is no parent file</param> 
public static void AddFileToProject(string project, string projectSubDir, 
     string file, string parent) 
{ 
    XDocument proj = XDocument.Load(project); 

    XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003"; 
    var itemGroup = proj.Descendants(ns + "ItemGroup").FirstOrDefault(x => x.Descendants(ns + "Compile").Count() > 0); 

    if (itemGroup == null) 
     throw new Exception(string.Format("Unable to find an ItemGroup to add the file {1} to the {0} project", project, file)); 

    //If the file is already listed, don't bother adding it again 
    if(itemGroup.Descendants(ns + "Compile").Where(x=>x.Attribute("Include").Value.ToString() == file).Count() > 0) 
     return; 

    XElement item = new XElement(ns + "Compile", 
        new XAttribute("Include", Path.Combine(projectSubDir,file))); 

    //This is used to group files together, in this case the file that is 
    //regenerated is grouped as a dependent of the user-editable file that 
    //is not changed by the code generator 
    if (string.IsNullOrEmpty(parent) == false) 
     item.Add(new XElement(ns + "DependentUpon", parent)); 

    itemGroup.Add(item); 

    proj.Save(project); 

} 
+0

你好, 我們一直在考慮將這樣的功能添加到CodeSmith中。你如何在你的模板中執行這段代碼? 感謝 -Blake Niemyjski – 2010-06-14 14:35:31

+0

在我的模板我打電話到我的輔助類,它看起來像這樣: 如果(創建== FALSE){ Helper.AddFileToProject(ModelProject,的String.Empty,文件名,parentName); } – Dugan 2010-06-14 17:58:15

0

你有沒有想過只編譯一個共享程序集(DLL),然後可以被所有的項目引用?

我知道這可能不適合您的要求,但我會認爲這將是實現所有項目可以使用的單一來源的最佳方法之一,並且也只有一個代碼庫可以根據需要進行維護。

+0

不幸的是這不適合我的情況下工作,但不是一個壞的可能的解決方案。 – Dugan 2010-06-07 15:05:25

相關問題