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.

Búsqueda de Computadoras en ActiveDirectory con C# .NET

Con Microsoft ActiveDirectory podemos realizar búsquedas de cualquier elemento en el dominio, entre ellos, las computadoras. En el siguiente artículo veremos de manera breve y sencilla cómo buscarlos.

Los objetos (o clases) a utilizar, serán los encontrados en la librería System.DirectoryServices.AccountManagement (Dll: System.DirectoryServices.AccountManagement.dll) indicando, que la misma, está disponible a partir del .NET Framework 3.5

Buscar equipo por ID/Nombre:

...
var context = new PrincipalContext(ContextType.Domain);
return ComputerPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "EQUIPO-MARIA");
...

Lo anterior, de encontrar una coincidencia, retornará un único elemento ComputerPrincipal donde:

  • ‘EQUIPO-MARIA’: Es un System.String indicando el nombre del equipo a buscar.
  • IdentityType: Es un enum que contiene otros valores como Name y es usado para indicar por cuál campo/propiedad se buscará.

Buscar equipo por último inicio de sesión:

...
var context = new PrincipalContext(ContextType.Domain);
return ComputerPrincipal.FindByLogonTime(context, date, MatchType.LessThan);
...

Lo anterior, retornará un listado de ComputerPrincipal con los equipos que accedieron al dominio antes de la fecha indicada donde:

  • date: Es un System.DateTime indicando la fecha límite.
  • MatchType.LessThan: Es un enum que contiene otros valores como GreaterThan e Equals.

Sencillo ¿no? Happy Coding ✌

Creación y Búsqueda de usuarios en ActiveDirectory

Hoy le toca a Microsoft Active Directory (AD) el artículo técnico. Pero…

¿Qué es AD?

De forma sencilla se puede decir que es un servicio establecido en uno o varios servidores en donde se crean objetos tales como usuarios, equipos o grupos, con el objetivo de administrar los inicios de sesión en los equipos conectados a la red, así como también la administración de políticas en toda la red. Su estructura jerárquica permite mantener una serie de objetos relacionados con componentes de una red, como usuarios, grupos de usuarios, permisos y asignación de recursos y políticas de acceso.- Wikipedia

Sigue leyendo