0

My dev machine is sitting in local LAN, with a local static IP address. And the emulator is basically another device, so app should use the local static IP address rather than localhost or 127.0.0.1. So I have such hard coded base URI:

                var baseUri = new Uri("http://192.168.0.8:9030/webapi/");

It is not nice if the other developers need to test the code. I am thinking of putting the base uri in a config file, and before deploying the emulator, update the config file with the local IP address of the dev machine.

Is there built-in config file or build mechanism in Xamarin for such purpose? or how would you test with Web API with local IIS and local emulator?

I am using Visual Studio 2017 Professional.

ZZZ
  • 2,752
  • 2
  • 25
  • 37

1 Answers1

2
  1. The Android emulator has a virtual/dedicated private subnet that it uses and the IP of 10.0.2.2 is what the emulator maps the host system to (so 10.0.2.2 on the emulator is the host's localhost/127.0.0.1).

  2. You certainly can add a text file (json/xml/etc..) to the project and load/read an IP value from it at runtime.

    a. Assembly Embedded File: How to read embedded resource text file

    b. Instead of using an assembly embedded file, you can use the native platform application read-only bundle to store your config file and read it at runtime from your native app or .NetStd library. (Note: I prefer this method over assembly embedding.)

Xamarin.Essentials' OpenAppPackageFileAsync provides an easy way to access read-only bundled files in your application (AndroidAssets, BundleResource, etc..)

using (var stream = await FileSystem.OpenAppPackageFileAsync("sushiConfig.json"))
{
    using (var reader = new StreamReader(stream))
    {
        var fileContents = await reader.ReadToEndAsync();
    }
}
SushiHangover
  • 73,120
  • 10
  • 106
  • 165
  • Is there a built-in way to update the config file with the Web API IP address? I know how to change a json file through commandline, however, would prefer to use what out of the box. – ZZZ Jul 30 '18 at 22:19
  • @ZZZ In Xamarin.iOS|Android applications there is no built in "config" file that mirrors a web.config file (or some other .Net standard convention). In terms of "native" app support, there are `plists` in iOS and the app manifest in Android, adding a iOS plist file as an `BundleResource` would be the closest equal, but the Android manifest was a predefined schema so it is not really an option. – SushiHangover Jul 30 '18 at 22:30
  • @ZZZ So adding a text-based file in a format of your choice is the way to go, also you could define #if/#else blocks and define `const` string variables to define what IP address to use depending upon how the project is compiled. – SushiHangover Jul 30 '18 at 22:32