How to read appSettings JSON from Class Library in ASP.NET Core

Hi, in this post we’ll show you how to read the appSettings.json file in your ASP.NET Core application from another library.

First

Having both projects, we proceed to add the following NuGet packages to the class library:

Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Abstractions (this will be installed anyways)
Microsoft.Extensions.Configuration.Json

configuration-nuget-packages

Second

Let’s edit your appsettings.json file adding a ConnectionString and a section with one value:

{
     "ConnectionStrings": {
         "DataConnection": "Server=.;Database=AppStore;Trusted_Connection=True;MultipleActiveResultSets=true;Integrated Security=True;"
     },
     "ApplicationSettings": {
         "Sample": "sample-text-yay!"
     }
 }

 

Third

Create a class for managing the reads, let’s say ‘AppConfiguration‘ and create your ConfigurationBuilder adding a JSON file as IConfigurationSource:

var configurationBuilder = new ConfigurationBuilder();
var path = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");
configurationBuilder.AddJsonFile(path, false);

...

public class AppConfiguration : IAppConfiguration
{

    private readonly string _sqlConnection;
    private readonly string _sample;

    public AppConfiguration()
    {
        var configurationBuilder = new ConfigurationBuilder();
        var path = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");
        configurationBuilder.AddJsonFile(path, false);

        var root = configurationBuilder.Build();
        _sqlConnection = root.GetConnectionString("DataConnection");

        var appSetting =  root.GetSection("ApplicationSettings");
        var test = appSetting["Sample"];
    }

    public string SqlDataConnection
    {
       get => _sqlConnection;
    }

    public string Sample
    {
     get => _sample;
    }
}

If you have problems when executing or deploying the app, probably the app is missing his configuration file.

1.- Check the Path you’re reading in the AppConfiguration
2.- Add the following code to your project.json file in the Core app:

"buildOptions": {
 "copyToOutput": {
 "include": [ "appsettings.json" ]
 }

Then the app builder will always copy the file.

 

References

 

Anuncios

Script for Extracting Files with Passwords

For this occasion we’ll have a batch script for extracting files protected with a password. The code:

echo off
setlocal EnableDelayedExpansion

set OriginSrc="C:\Users\Michael\My Documents\Galleries\Birthdays\20170415-Images.7z"
set Destination="Images"
echo %DestDir%

set Password=mypass

rmdir %Destination%
"C:\Program Files\7-Zip\7z.exe" e "%OriginSrc%" -y -p%Password% -o"%Destination%

 

If the passed password was the one we’ll see something like this:

cmd-result

Otherwise, will result in an error and you’ll need to change the password.

How to remove/update default Home page in Azure Mobile Apps

Today, playing around with the Azure Mobile Apps platform, wanted to do some deep customization to the project, one of them: change the Default Blue-styled Home Page. After some research and looking through the Azure Mobile Server GitHub project, i’ve got it done!

For that we’ll be doing these steps:

  • Remove reference to Microsoft.Azure.Mobile.Server.Home
  • Change some lines in Startup.cs (Routes and MobileAppConfiguration initialization)
  • Create a Controller.
  • Create an HTML page as an Embedded Resource

 

First, let’s add our Controller and HTML files

Create an ApiController, maybe called ‘HomeController‘ and put this code:

[ApiExplorerSettings(IgnoreApi = true)]
public class HomeController : ApiController
{
     [HttpGet]
     [AllowAnonymous]
     public IHttpActionResult Index()
     {
         return new StaticHtmlActionResult("MyNamespace.WebApi.Home.html");
     }
}

Ref 1

After that, add an HTML page (matching the prefix in the string passed to the StaticHtmlActionResult call) to the main folder of the project and at the Properties tab change the Build Action to Embedded Resources.

Second, to change the Startup.MobileApp.cs file

We need to add a route mapping with our custom Controller and change the actual MobileAppConfiguration implementation (if using the default one):

var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
        name: "Home",
        routeTemplate: string.Empty,
        defaults: new { controller = "Home", action = "Index" });

new MobileAppConfiguration()
             .MapApiControllers()
             .AddTables(
                        new MobileAppTableConfiguration()
                             .MapTableControllers()
                             .AddEntityFramework()
             )
             .ApplyTo(config);

With that, we’re already redirecting our calls to our new HTML page.

Notice that we aren’t using the key extensions method commonly used: AddMobileHomeControllerPage and UseDefaultConfiguration functions.

Finally, let’s remove a Dll reference

If you have been looking the Azure Mobile App’s GitHub project, will notice how the page display is done. All that logic is thanks to few lines in the Microsoft.Azure.Mobile.Server.Home nuget package. Since we already have a reference to it, if we try to run the application we’ll receive an error indicating that ‘Multiple matches found‘. Why? Because config.Routes has two routing matching the same pattern. Fix? Delete the reference and let it be!

You’ll finally be able to show something like this:

custom-azure-mobile-homepage

You can look an example of this implementation in the following GitHub project.

Minientrada

Articles Microsoft Office 365 vs Google Apps

Looking the differences between Microsoft Office 365 vs Google Apps? These compilations of links may help you:

Nuestra privacidad digital [Opinión]

MEGA, es un servicio de almacenamiento en la nube (File Cloud Storage): Ofrece 50GB de almacenamiento gratis, dispone de un alto mecanismo de privacidad, a tal punto, que si pierdes la contraseña (utilizada para encriptar/codificar tus archivos), pierdes acceso a los mismos. Posee aplicaciones en la mayoría de plataformas (móviles y no móviles) y una aplicación Web.

Hoy, hace unas horas me he enterado de que Kim DotCom (fundador del servicio de almacenamiento en la nube MEGA), ha dicho públicamente que debido a la alta adquisición de acciones por parte de un inversionista chino acusado de fraude, ya no confía en la integridad de los servicios de MEGA y ha renunciado/salido de la entidad corporativa.

¿A qué viene todo esto? Pues que ahora, aquellos usuarios que se sentían seguros en MEGA, buscarán alternativas, nuevas opciones que puedan satisfacer sus necesidades (sí, la privacidad es una de ellas) tanto técnicas como económicas. [Ver Almacenamiento en línea y alternativas a MEGA]
Sigue leyendo