如何以编程方式提取应用程序名称和版本号?

时间:2013-01-12 01:41:15

标签: c# exception-handling error-handling windows-phone-8 azure-mobile-services

我想在UnhandledException事件中填充WAMS表,我已经得到了这段代码:

private async void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs args)
{
    if (Debugger.IsAttached)
    {
        // An unhandled exception has occurred; break into the debugger
        Debugger.Break();
    }
    PLATYPIRUS_WAMS_EXCEPTIONLOG pruwamsel = new PLATYPIRUS_WAMS_EXCEPTIONLOG();
    pruwamsel.appNameAndVersion = "Platypi R Us for WP8 v. 3.14";
    pruwamsel.ExceptionMsg = args.ExceptionObject.Message;
    pruwamsel.InnerException = args.ExceptionObject.InnerException.ToString();
    pruwamsel.ExceptionToStr = args.ToString();
    pruwamsel.dateTimeOffsetStamp = DateTimeOffset.UtcNow;
    await App.MobileService.GetTable<PLATYPIRUS_WAMS_EXCEPTIONLOG>().InsertAsync(pruwamsel); 
}

...但我真的不想硬编码应用名称和版本。如何以编程方式提取这些?

更新

结合这两个想法,我最终得到:

private async void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs args)
{
    if (Debugger.IsAttached)
    {
        // An unhandled exception has occurred; break into the debugger
        Debugger.Break();
    }

    string appName;
    string appVersion;
    var xmlReaderSettings = new XmlReaderSettings
    {
        XmlResolver = new XmlXapResolver()
    };

    using (var xmlReader = XmlReader.Create("WMAppManifest.xml", xmlReaderSettings))
    {
        xmlReader.ReadToDescendant("App");

        appName = xmlReader.GetAttribute("Title");
        appVersion = xmlReader.GetAttribute("Version");
    }

    PLATYPIRUS_WAMS_EXCEPTIONLOG pruwamsel = new PLATYPIRUS_WAMS_EXCEPTIONLOG();
    pruwamsel.appNameAndVersion = string.Format("{0} {1}", appName, appVersion);
    pruwamsel.ExceptionMsg = args.ExceptionObject.Message;
    pruwamsel.InnerException = args.ExceptionObject.InnerException.ToString();
    pruwamsel.ExceptionToStr = args.ExceptionObject.ToString();
    pruwamsel.dateTimeOffsetStamp = DateTimeOffset.UtcNow; 
    await App.MobileService.GetTable<PLATYPIRUS_WAMS_EXCEPTIONLOG>().InsertAsync(pruwamsel); 
}

1 个答案:

答案 0 :(得分:3)

应用程序名称和版本在WMAppManifest.xml文件中注册。

通过使用此this sample并将“ProductID”部分替换为“Title”和“Version”,我设法获得此代码:

var xmlReaderSettings = new XmlReaderSettings
{
    XmlResolver = new XmlXapResolver()
};

using (var xmlReader = XmlReader.Create("WMAppManifest.xml", xmlReaderSettings))
{
    xmlReader.ReadToDescendant("App");

    var AppName = xmlReader.GetAttribute("Title");
    var AppVersion = xmlReader.GetAttribute("Version");
}