Генерация WMAppManifest.xml с T4
У меня есть класс, который просто возвращает значения в AssemblyInfo.cs (этот код для Windows Phone):
using System.Runtime.InteropServices;
using System.Reflection;
namespace Tiletoons
{
class AppInfo
{
public static readonly string Id = string.Empty;
public static readonly string Product = string.Empty;
public static readonly string Company = string.Empty;
public static readonly string Version = string.Empty;
static AppInfo()
{
Assembly assembly = Assembly.GetExecutingAssembly();
foreach (object attribute in assembly.GetCustomAttributes(false)) {
if (attribute.GetType() == typeof(GuidAttribute)) {
Id = (attribute as GuidAttribute).Value;
} else if (attribute.GetType() == typeof(AssemblyProductAttribute)) {
Product = (attribute as AssemblyProductAttribute).Product;
} else if (attribute.GetType() == typeof(AssemblyCompanyAttribute)) {
Company = (attribute as AssemblyCompanyAttribute).Company;
}
}
Version = assembly.FullName.Split('=')[1].Split(',')[0];
}
}
}
... Я хотел бы использовать его для автоматической генерации моего файла WMAppManifest.xml через преобразования T4; Вот мой файл ttinclude:
<#@ assembly name="System.Core" #>
<#@ assembly name="EnvDTE" #>
<#@ import namespace="EnvDTE" #>
<#@ import namespace="System" #>
<#
IServiceProvider hostServiceProvider = Host as IServiceProvider;
EnvDTE.DTE dte = hostServiceProvider.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
EnvDTE.ProjectItem containingProjectItem = dte.Solution.FindProjectItem(Host.TemplateFile);
Project project = containingProjectItem.ContainingProject;
var projectName = project.FullName;
ProjectItem deploymentConfiguration = GetProjectItem(project, "AppInfo.cs");
if (deploymentConfiguration == null) {
throw new Exception("Unable to resolve AppInfo.cs");
}
var codeModel = deploymentConfiguration.FileCodeModel;
string id = null;
string product = null;
string company = null;
string version = null;
foreach (CodeElement codeElement in codeModel.CodeElements) {
if (codeElement.Name == "AppInfo") {
CodeClass codeClass = codeElement as CodeClass;
foreach (CodeElement memberElement in codeClass.Members) {
CodeVariable variable = memberElement as CodeVariable;
switch (memberElement.Name) {
case "Id":
id = variable.InitExpression as string;
break;
case "Product":
product = variable.InitExpression as string;
break;
case "Company":
company = variable.InitExpression as string;
break;
case "Version":
version = variable.InitExpression as string;
break;
}
}
}
}
#>
<#+ EnvDTE.ProjectItem GetProjectItem(Project project, string fileName)
{
foreach (ProjectItem projectItem in project.ProjectItems) {
if (projectItem.Name.EndsWith(fileName)) {
return projectItem;
}
var item = GetProjectItem(projectItem, fileName);
if (item != null) {
return item;
}
}
return null;
}
EnvDTE.ProjectItem GetProjectItem(EnvDTE.ProjectItem projectItem, string fileName)
{
if (projectItem.ProjectItems != null && projectItem.ProjectItems.Count > 0) {
foreach (ProjectItem item in projectItem.ProjectItems) {
if (item.Name.EndsWith(fileName)) {
return item;
}
}
}
return null;
}
#>
... и, наконец, вот мой шаблон манифеста:
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ output extension=".xml" #>
<#@ include file="AppInfo.ttinclude" #>
<?xml version="1.0" encoding="utf-8"?>
<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2009/deployment" AppPlatformVersion="7.0">
<App xmlns="" ProductID="<#= id #>" Title="<#= product #>" RuntimeType="XNA" Version="<#= version #>" Genre="apps.games" Author="Gonzo" Description="<#= description #>" Publisher="<#= company #>">
<IconPath IsRelative="true" IsResource="false">
...
</App>
</Deployment>
Можно ли заполнить шаблон манифеста с помощью такого класса, как мой (AppInfo)? Я не хочу повторять константы, уже определенные в AssemblyInfo.cs, то есть идея состоит в том, чтобы просмотреть всю информацию, необходимую для публикации моего приложения WP, оттуда.
Любая идея будет действительно приветствоваться:-)
J3D
1 ответ
Ну, у меня есть две разные конфигурации развертывания для моего приложения (облегченная версия или профессиональная версия), и для каждой конфигурации мне нужен определенный Guid, название заголовка, версия и т. Д. Я смог решить свою проблему, изменив WMAppManifest.tt следующим образом:
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ output extension=".xml" #>
<#@ assembly name="$(TargetPath)" #>
<?xml version="1.0" encoding="utf-8"?>
<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2009/deployment" AppPlatformVersion="7.0">
<App xmlns="" ProductID="<#= AppInfo.Id #>" Title="<#= AppInfo.Product + " " + AppInfo.Edition #>" RuntimeType="XNA" Version="<#= AppInfo.Version #>" Genre="apps.games" Author="Gonzo" Description="<#= AppInfo.Description #>" Publisher="<#= AppInfo.Company #>">
...
</App>
</Deployment>
В приведенном выше фрагменте кода я указал $(TargetPath) в директиве сборки (это указывает на мою скомпилированную сборку в каталоге bin), и в итоге я смог получить пользовательские атрибуты из AssemblyInfo. Таким образом, я просто определяю Guids и другие необходимые данные только один раз - вот часть моего AssemblyInfo:
...
#if !LITE_EDITION
[assembly: Guid("716ab9de-f88e-9a14-8d81-65sn67dbf99e")]
[assembly: AssemblyEdition("Pro")]
#else
[assembly: Guid("91e6742f-6273-1a8b-55a69-e70ad5644827")]
[assembly: AssemblyEdition("Lite")]
#endif
...
В зависимости от текущей конфигурации (например, Debug, Debug Lite, Release, Release Lite), я генерирую манифест приложения с правильной информацией. Надеюсь, это поможет.
J3D