#Net5 – Migrating a fully functional Windows Form app to Net 5 in 10 minutes !

Buy Me A Coffee

Hi !

TbVolScroll is a super cool project, take a look 👇

Simple utility to enable volume control when your mouse cursor is positioned above the taskbar.
Hold the left ALT key to enable precise volume control (decrease/increase volume by 1%). Standard volume step is 5%. The volume bar will follow the cursor when it’s moved.
By default, if the volume is lower than 10% precise volume control is automatically enabled.

TbVolScroll

Note: As far as I remember, this feature is available in other OS.

And thanks to his author the code of the tool is available in GitHub (see references).

The original project is a .Net Framework 4.7.2 project, so I decided to test how much time it will take to migrate the project to .Net 5. I didn’t perform a deep analysis of the source project, before start. This is my labs migration path

  • Create a new Windows Form Net 5 project named [TbVolScrollNet5]
  • Copy all the files from the original project, avoiding the .csproj file
  • Rebuild !

And it worked ! I mean, I fixed some namespaces, added a missing NuGet package and 10 minutes later it was working. Of course, I submitted a pull request with the migration project, in the meantime I will keep this local just for fun.

And I want to use it ! So now is the time to pack and publish a local version of the tool. I created a local publish profile and defined

  • Build in Release | Any CPU
  • Deployment as Self-Contained
  • Runtime win-x86
  • Produce as single file
  • Enable ReadyToRun compilation
tbvolscroll publish profile as self contained

And that’s it! 150 MB to a fully functional working app 👇😸👇

tbvolscroll published version

Now back to work, and in my next steps I’ll publish this as a clickonce app so it’s easy to distribute. And the perfect excuse to learn more about .Net 5 !

References


¿Con ganas de ponerte al día?

En Lemoncode te ofrecemos formación online impartida por profesionales que se baten el cobre en consultoría:

#VS2017 – Lessons learned migrating a UWP App from #Windows 8.1 to #Windows10 and how to replace Geolocation CivicAddress

Hi!

If you ever get bored, an 100% interesting activity is to try to update a project that has been closed 3 years ago or more. In my case, I have invested much time during these past days upgrading a Windows 8.1 to Windows 10 App.

Here’s a couple of things I’ve learned

  • Visual Studio 2017 is a thousand times better than previous Visual Studio versions to create UWP Apps. This point applies the saying “for tastes colors” in my case Visual Studio 2017 works great!
  • 3 years ago the most advisable option to share code/functionality between projects were to use Portable Class Libraries. Today this is very Old School, so I have migrated several projects to .Net Standard and it was not an easy path (ostias!)
  • I have suffered, in silence but pain was there. For example, .Net Standard its now in version 2.0, however, in order to create Net standard Class Libraries that can be used in UWP Apps, you have to “download” to version 1.4
  • No more CivicAddress. If you use localization functionality in your App, including values such as the country, city, zip code and State, the CivicAddress property has been declared obsolete from win 8.1

On this last point I will extend a bit. Well When you get the location in a UWP App, the 2 values that if returned are latitude and longitude. I was investigating a little bit about the best way to get an address from a point (latitude and longitude) and I came to this conclusion.

You can use services like the following where you must have a Developer key

Although thanks to StackOverflow I found a free service that with 4 lines solves the problem. This is OPENSTREETMAP and the following code is more than enough to understand how it works

public async Task<Tuple<string, string, string, string>> ResolveCountryAndCityNameAsync(double latitude, double longitude, string appName)
{
var lat = latitude.ToString(CultureInfo.InvariantCulture).Replace(",", ".");
var lon = longitude.ToString(CultureInfo.InvariantCulture).Replace(",", ".");
var requestUri = $"http://nominatim.openstreetmap.org/reverse?format=xml&zoom=18&lat={lat}&lon={lon}&application={appName}";
var client = new HttpClient();
var resTask = client.GetStringAsync(requestUri);
var res = await resTask;
var resultDocument = XDocument.Parse(res);
var addressElement = resultDocument.Root.Element("addressparts");
var city = addressElement.Element("city").Value;
var country = addressElement.Element("country").Value;
var postalCode = addressElement.Element("postcode").Value;
var state = addressElement.Element("state").Value;
var result = new Tuple<string, string, string, string>(country, city, postalCode, state);
return result;
}

A sample result in the next image

I1

that if, if your application requires a very intense use of this service, it is time to go back to Bing or Google to avoid a

System.Net.Http.HttpRequestException: ‘Response status code does not indicate success: 429 (Too Many Requests).’

I2

Happy Coding!

Greetings @ Toronto

El Bruno

References

#VS2017 – Lecciones aprendidas migrando una UWP App de #Windows 8.1 a #Windows10 y como reemplazar GeoLocation.CivicAddress

Buenas!

Si alguna vez te aburres, una actividad 100% interesante es intentar actualizar un proyecto que se ha cerrado hace 3 años o más. En mi caso, he invertido gran parte de estos últimos días en actualizar una App de Windows 8.1 a Windows 10.

He aquí un par de cosas que he aprendido

  • Visual Studio 2017 es mil veces mejor que las versiones anteriores para crear UWP Apps. Este punto se aplica el dicho “para gustos colores”, en mi caso VS2017 vuela.
  • Hace 3 años la opción mas recomendable para compartir código / funcionalidad entre proyectos eran Portable Class Libraries. Hoy esto es muy Old School, he migrado varios proyectos a .Net Standard y algún par de ostias he sufrido
  • Por ejemplo, .Net Standard va por su versión 2.0, sin embargo, para poder crear Net Standard Class Libraries que se puedan utilizar en UWP Apps, hay que “bajar” hasta la versión 1.4
  • No more CivicAddress. Si utilizas funcionalidades de localización en tu App, incluyendo valores como el país, ciudad, código postal y estado, la propiedad CivicAddress ha sido declarada obsoleta desde Win8.1

Sobre este último punto me extenderé un poco. Pues bien, cuando obtienes la ubicación en una UWP App, los 2 valores que si se retornan son latitud y longitud. Estuve investigando un poco sobre la mejor forma de obtener una dirección a partir de un punto (latitud y longitud) y llegué a esta conclusión

Puedes utilizar servicios como los siguientes donde debes tener una clave de Developer

Aunque gracias a StackOverflow encontré un servicio gratuito que con 4 líneas me resuelve el problema. Se trata de OpenStreetMap y el siguiente código es mas que suficiente para comprender como funciona

public async Task<Tuple<string, string, string, string>> ResolveCountryAndCityNameAsync(double latitude, double longitude, string appName)
{
var lat = latitude.ToString(CultureInfo.InvariantCulture).Replace(",", ".");
var lon = longitude.ToString(CultureInfo.InvariantCulture).Replace(",", ".");
var requestUri = $"http://nominatim.openstreetmap.org/reverse?format=xml&zoom=18&lat={lat}&lon={lon}&application={appName}";
var client = new HttpClient();
var resTask = client.GetStringAsync(requestUri);
var res = await resTask;
var resultDocument = XDocument.Parse(res);
var addressElement = resultDocument.Root.Element("addressparts");
var city = addressElement.Element("city").Value;
var country = addressElement.Element("country").Value;
var postalCode = addressElement.Element("postcode").Value;
var state = addressElement.Element("state").Value;
var result = new Tuple<string, string, string, string>(country, city, postalCode, state);
return result;
}

El resultado que retorna este servicio es similar a

I1

Eso si, si tu aplicación requiere un uso muy intenso de este servicio, es momento de volver a Bing o a Google para evitar un

System.Net.Http.HttpRequestException: ‘Response status code does not indicate success: 429 (Too Many Requests).’

I2

Happy Coding!

Saludos @ Toronto

El Bruno

References