Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetEntryAssembly from Portable Class Library (Profile 158)

I would like to get the name of the entry assembly, e.g., myApp.exe. Previously in net45, I would use Assembly.GetEntryAssembly, but this is not available in Profile 158. Are there any alternatives? (Could I chain Assembly.GetCallingAssembly all the way back?) Any tips much appreciated.

Using GetEntryAssembly, I can determine the name of the application. I use this name for the UserAgent in HttpClient calls as well as for naming files and tagging feedback with the originating application. Alternative methods to get the name of the application would be appreciated.

like image 555
tofutim Avatar asked Dec 12 '13 22:12

tofutim


1 Answers

To get the name of the application

You'll have to deal with the hard fact that Assembly.GetEntryAssembly() is not available in Store and Phone apps. So isn't available to you either, your library could not work in such an app. Workarounds can be hard to come by for missing .NET Framework support, but this is an easy one. Whatever application uses your library never has any trouble providing you with this information. Either because it doesn't have the restriction of using GetEntryAssembly() or, of course, because it knows what its logical name is.

So just expose a property to let the client programmer tell you about it. Just provide a Really Good exception message so he'll instantly know when he forgets. Something like:

    public static string ApplicationName {
        get {
            if (_applicationName == null) {
                throw new InvalidOperationException("You *must* assign the ApplicationName property before this library is usable");
            }
            return _applicationName;
        }
        set { _applicationName = value; }
    }
    private static string _applicationName;

Be sure to use the property in your own code instead of the private field so the exception is reliably raised.

So now a Store app programmer will simply hard-code the property assignment in his App constructor:

    public App()
    {
        this.InitializeComponent();
        this.Suspending += OnSuspending;
        YourPclLibrary.ApplicationName = "MyBeautifulSoup";
        // etc...
    }

Allowing the client programmer to pass an app name through a class constructor is of course also a perfectly legitimate (and preferable) approach.

like image 150
Hans Passant Avatar answered Nov 12 '22 14:11

Hans Passant