Misc

Setting file permissions on a remote machine with PowerShell

Recently I needed to set some file permissions on a remote machine. Previously I’d done this relatively easily through a share as the user account I was using also had administrator rights on the other side and I was dealing with domain accounts. However, this did not work for a user that was local to the remote machine.

So, I creates a small PowerShell function to remotely set the user to a local (or any domain) account. (This also works for virtual accounts like IIS AppPool/ users)

function Add-RemoteAcl
(
    [string]$computerName,
    [string]$directory,
    [string]$user,
    [string]$permission
)
{
    $session = New-PSSession -ComputerName $computerName;
    Invoke-Command -Session $session -Args $directory, $user, $permission -ScriptBlock {
        param([string]$directory,[string]$user,[string]$permission)
        $acl = Get-Acl $directory;
        $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($user, $permission, "ContainerInherit, ObjectInherit", "None", "Allow");
        if ($accessRule -eq $null){
            Throw "Unable to create the Access Rule giving $permission permission to $user on $directory";
        }
        $acl.AddAccessRule($accessRule)
        Set-Acl -aclobject $acl $directory
    };
    Remove-PSSession $session;
}

To run the PowerShell remotely, first of all, I create a new PowerShell session on the remote machine with New-PSSession, then I run a script in that session with Invoke-Command, and finally I clean up with Remove-PSSession to end the remote session.

Bear in mind that you will need the appropriate permissions on the remote machine for whatever actions you want to take.

Invoke-Command

This is where all the work is done. You can pass a session to Invoke-Command, and you can also pass an ArgumentList to pass in to the command. This gives it some fantastic abilities.

Be aware that variables that exist outside the script block are not visible within the script block, you have to pass them as an ArgumentList (alias Args), and the script block has to pick them up. Hence the code above starts the script block with a params section in order to pick up the values passed as the Args.

Setting the file permissions

In order to add new rules to an ACL you have to Get-Acl to get the existing set of rules, create the new FileSystemAccessRule for the permission you want to grant, then AddAccessRule to the ACL you retrieved, and finally Set-Acl to persist the addition.

If you were just to create the new rule and set that, then all the existing rules would be replaced with the one rule that was just created.

Misc

IIS Administration file access

If you are using the IIS Administration ReST API to manage IIS, one thing that is not immediately obvious is that if you put your websites outside of %systemdrive%\inetpub you won’t be able to access them through the API. e.g. You won’t be able to set the physical path of a website to a location outwith %systemdrive%\inetpub.

If you do try to set the file outwith the default location, then you will get an 403 error from the API with a JSON response that looks like this:

{
    "title":"Forbidden",
    "name":"physical_path",
    "detail":"C:\\www\\MyWebSite",
    "status":403
}

So, you need to update its settings file (in my case, located at C:\Program Files\IIS Administration\2.2.0\Microsoft.IIS.Administration\config\appsettings.json) to include a files section. The files section is at the same level as security, logging, cors, etc.

e.g.

  "files": {
    "locations": [
      {
        "alias": "www",
        "path": "c:\\www",
        "claims": [
          "read"
        ]
      }
    ]
  }

This will allow websites/web-applications to be located in C:\www

Remember to restart the “Microsoft IIS Administration” Service after making changes to the appsettings.json file so that it will be picked up.

Restarting Microsoft IIS Administration Service
Restart Microsoft IIS Administration Service

You can also check which files IIS Administration has access to through the API. The end-point is /api/files/ and, if there are no files set up it will show an empty JSON array for the files part of the result.

API Result showing empty files section
API Result showing empty files section

Once the files section is added to the appsettings.json file and the Microsoft IIS Administration service is restarted, the API will show which files the API can access.

Populated file section in the IIS Administration API
Populated file section in the IIS Administration API

Finally, if you are having difficulty saving the appsettings.json file, read how to take ownership of a file in order to be able to be able to write to it.

Updates

Updated 14/March/2018: Note to restart the Windows Service; Show what files are available through the API; formatting.

Misc

Taking ownership of a file

I’m currently looking at using IIS Administration as a way to automate some deployment tasks. However, the way it got installed, it’s appsettings.json file could not be written to, even when running the text editor as Administrator.

It turns out, SYSTEM had full control of the file, and the installer configured it to only allow me to access the ReST API, yet I needed a deployment script running from the Continuous Delivery server to be able to access IIS Administration, so I needed to modify the settings file, somehow.

To take ownership – The quick guide

So, to take ownership of the appsettings.json file, what I needed was to run two commands at command prompt running as Administrator.

takeown /f "appsettings.json" /a

icacls "appsettings.json" /grant administrators:F /c /l

TAKEOWN

/f [filename] : Specifies the file or directory name, can contain wildcards.

/a : Optional, gives the ownership to the Administrators group, rather than the current user.

 

ICACLS

/grant [sid]:[permission] : Where sid is the name of the user or group, and [permission] is the permission set, in this case F for “full access”

/C : Indicates to continue on error

/L : Indicates the operation will run on the symbolic link itself, rather than the target of the link.

Software Development

Paramore Brighter: Implementing a fallback exception handler

So far in this series, we have a basic command processor set up and able to dispose of resources. But what happens when things go wrong? The command processor has a fallback mechanism to handle exceptions that are not caught.

To add this functionality all you need to do is to decorate your handler with a fallback policy attribute, add the Fallback handler into your Dependency Injection framework, and then override the Fallback method.

To add the Fallback handler to .NET Core’s Dependency Injection framework we add

serviceCollection.AddScoped(typeof(FallbackPolicyHandler<>));

to the BuildServiceProvider method. The typeof variant of AddScoped allows a more general type to be expressed. Otherwise, we’d have to add a fallback policy handler for each command.

Our little salutation handler now looks like this:

[FallbackPolicy(backstop:true, circuitBreaker:false, step:1)]
public override SalutationCommand Handle(SalutationCommand command)
{
    Console.WriteLine($"Greetings, {command.Name}.");
    ThrowOnTheDarkLord(command);
    return base.Handle(command);
}

(If you’ve not read Harry Potter, the reference is that if you use He-who-must-not-be-named’s name, then a death eater will appear and take you away. So if we use The Dark Lord’s name we’re throwing an exception)

Back to the code: The first line is the attribute decoration. In this case we say we have a fallback policy that acts as a backstop for any unhandled exception (backstop:true). We’ve not covered the Circuit Breaker so we’re not interested in that for the moment (circuitBreaker:false), and we’ve also not covered what happens if you have multiple attributes (step:1) so we’ll leave that as step 1 (of 1). I’ll come back to those things later.

Now, if we put “Voldemort” in as the Name in the command, it will throw an exception. So we have to handle that somehow. The RequestHandler class has a Fallback method which you can override in your derived handler class.

public override SalutationCommand Fallback(SalutationCommand command)
{
    if (this.Context.Bag
            .ContainsKey(FallbackPolicyHandler<SalutationCommand>
                         .CAUSE_OF_FALLBACK_EXCEPTION))
    {
        Exception exception = (Exception)this.Context
                              .Bag[FallbackPolicyHandler
                                   .CAUSE_OF_FALLBACK_EXCEPTION];
        Console.WriteLine(exception);
    }
    return base.Fallback(command);
}

What is happening here is that we are retrieving the Exception from the Context‘s Bag, which is just a Dictionary. Then we can do what we want with the Exception. In this simple example, I’m just writing it to the console, but you’ll most likely want to do something more with it in your application.

As you can see, this is a bit on the clunky side, so where I’ve used Brighter before, I’ve tended to introduce a class between RequestHandler and the specific handler to put in some things that help clean things up.

In this case the MyRequestHandler class looks like this:

public class MyRequestHandler<TCommand> 
             : RequestHandler<TCommand> where TCommand : class, IRequest
{
    public override TCommand Fallback(TCommand command)
    {
        if (this.Context.Bag
            .ContainsKey(FallbackPolicyHandler
                .CAUSE_OF_FALLBACK_EXCEPTION))
        {
            Exception exception = (Exception)this.Context
                .Bag[FallbackPolicyHandler
                    .CAUSE_OF_FALLBACK_EXCEPTION];
            return base.Fallback(ExceptionFallback(command, exception));
        }
        return base.Fallback(command);
    }

    public virtual TCommand ExceptionFallback(TCommand command, Exception exception)
    {
        // If exceptions need to be handled, 
        // this should be implemented in a derived class
        return command;
    }
}

At the top we can see that instead of a specific command we still have the generic TCommand, which needs to be a class and derived from IRequest. That wasn’t seen in the specific command handler because the explicit command already has these properties, so we didn’t need to express them again.

The Fallback method now contains the code that extracts the exception from the Context and calls ExceptionFallback. In this class ExceptionFallback does nothing except return the command back. When we implement it in our SalutationHandler, the code for handling the exception now looks like this:

public override SalutationCommand ExceptionFallback(SalutationCommand command, Exception exception)
{
    Console.WriteLine(exception);
    return base.ExceptionFallback(command, exception);
}

And that is so much nicer to read. We’ve extracted away the plumbing of retrieving the exception to the newly introduced base class and our command handler looks much neater as a result.

To view the source as a whole, see it on GitHub.

Software Development

Paramore Brighter: Ensuring Dependencies are Disposed.

In my previous post, I showed how to set up Paramore Brighter with the built in Dependency Injection provided with .NET Core 2. However, it wasn’t the full story.

The code for this post is on GitHub.

In reality the various classes you might need will have different lifecyles, and along with that there are different needs for cleaning up. Some objects might be singletons and you get the same object back every time, some might be transient where you get a different object back every time, and in some cases you need the same object back for the the duration of the action you are doing, but a different object back at other times.

We’re going to look at the last scenario, objects that have a “scope”. For example, say somewhere you need to access a DbContext from Entity Framework. You probably want the same context for the duration of handling the command, but a separate one next time around. This is especially true if your application can handle multiple commands at the same time (e.g. An ASP.NET Core application) – You don’t want one handler to initiate SaveChanges() on the same context as another is still making changes to the data model.

We also want to make sure that any objects that need to be disposed of at the end of handling a command are properly disposed of, whether it is the handler itself, or an object that was injected into it.

To that end we’re going to make some changes to the code from the previous application.

The BuildServiceProvider() method changes the handlers to being scoped:

private static IServiceProvider BuildServiceProvider()
{
    var serviceCollection = new ServiceCollection();
    serviceCollection.AddScoped<SalutationHandler>();
    return serviceCollection.BuildServiceProvider();
}

The ServiceProviderHandler class that was created in the previous post needs to take into account that after a command is handled, the resources it uses need to be disposed.

public class ServiceProviderHandler : IAmAHandlerFactory
{
    private readonly IServiceProvider _serviceProvider;
    private readonly ConcurrentDictionary<IHandleRequests, IServiceScope> _activeHandlers;
    public ServiceProviderHandler(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
        _activeHandlers = new ConcurrentDictionary<IHandleRequests, IServiceScope>();
    }
    public IHandleRequests Create(Type handlerType)
    {
        IServiceScope scope = _serviceProvider.CreateScope();
        IServiceProvider scopedProvider = scope.ServiceProvider;
        IHandleRequests result = (IHandleRequests)scopedProvider.GetService(handlerType);
        if (_activeHandlers.TryAdd(result, scope))
            return result;

        scope.Dispose();
        throw new InvalidOperationException("The handler could not be tracked properly. It may be declared in the service collection with the wrong lifecyle.");
    }

    public void Release(IHandleRequests handler)
    {
        if (_activeHandlers.TryRemove(handler, out IServiceScope scope))
        {
            scope.Dispose();
        }
    }
}

The changes are that we now keep a dictionary of active command handlers and the scope they are in. When we are asked to Create() a new handler, we:

  • create a new scope,
  • get a services in the context of that scope, and
  • store the handler and scope in the dictionary (keyed on the handler)

If the handler cannot be added to the dictionary, then we Dispose() of the scope (which also disposes the handler if it is disposable) and we throw an exception to say that something went wrong. Generally, the same handler should never end up in the dictionary twice, but it might if it was set up with a Singleton lifecycle and multiple threads are trying to use it. So, we guard against that. In a single threaded application, this code is not likely to be hit even if the handler was defined as a Singleton because it will have been removed from the dictionary at the end of its previous operation.

Once the command has been handled, the Release() method is called which

  • looks up the handler in the dictionary to get the scope, while it
  • removes the handler and scope from the dictionary, and then
  • disposes of everything in that scope.

Just to show that this all works, I made the command handler implement the IDisposable interface and just put in a Console.WriteLine() to show that it was called.

public class SalutationHandler : RequestHandler<SalutationCommand>, IDisposable
{
    public override SalutationCommand Handle(SalutationCommand command)
    {
        Console.WriteLine($"Greetings, {command.Name}.");
        return base.Handle(command);
    }

    public void Dispose()
    {
        Console.WriteLine("I'm being disposed.");
    }
}

The Main() method now creates two commands:

commandProcessor.Send(new SalutationCommand("Christian"));
commandProcessor.Send(new SalutationCommand("Alisdair"));

And the resulting output is:

Greetings, Christian.
I'm being disposed.
Greetings, Alisdair.
I'm being disposed.
Software Development

Paramore Brighter: Using .NET Core’s Dependency Injection

This is the first in a series of posts on Paramore.Brighter. I’m writing this as a series of recipes, with the aim of you picking up a point quickly and getting going with it.

The code for this post is on GitHub, you can find it here: GitHub Basic solution

In .NET Core there is now a Dependency Injection framework built in. Obviously, you can use your own, but for simplicity (and because a lot of people will take what comes in the box) I’m going to show you how to use the dependency injection framework that comes out of the box. It is what ASP.NET Core applications will use by default.

The Command & Handler

If you’ve already read a bit about how Paramore Brighter works, you’ll probably already know how to create commands and command handlers, but we’ll just recap anyway. We’re going to create a simple Hello World scenario.

Our command and handler look like this:

public class SalutationCommand : IRequest
{
    public Guid Id { get; set; }

    public string Name { get; }

    public SalutationCommand(string name)
    {
        Id = Guid.NewGuid();
        Name = name;
    }
}

public class SalutationHandler : RequestHandler<SalutationCommand>
{
    public override SalutationCommand Handle(SalutationCommand command)
    {
        Console.WriteLine($"Greetings, {command.Name}.");
        return base.Handle(command);
    }
}

Nothing too complex here. The command is used to pass some information to the handler, in this case a name, we’ll not worry about the Id for the moment, it is required by the IRequest interface, and at this stage can be anything you want. The handler then writes a greeting to the console using the name it was given.

Configuring the command processor

At a most basic level, the command processor needs to know just two things.

  1. How to map commands to their handler
  2. How to build a handler

Everything else it can do can come later, but without those two things it does not work.

The first thing the configuration does it build a registry of commands and their handlers.

private static SubscriberRegistry CreateRegistry()
{
    var registry = new SubscriberRegistry();
    registry.Register<SalutationCommand, SalutationHandler>();
    return registry;
}

The second thing it does is create a class, implementing the IAmAHandlerFactory interface, that will build the handler, and in our case, it uses the IServiceProvider to do that.

public class ServiceProviderHandler : IAmAHandlerFactory
{
    private readonly IServiceProvider _serviceProvider;
    public ServiceProviderHandler(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }
    public IHandleRequests Create(Type handlerType)
    {
        return (IHandleRequests)_serviceProvider.GetService(handlerType);
    }

    public void Release(IHandleRequests handler)
    {
    }
}

This is a very simple implementation that just calls the GetService() in the Create() method to get the command handler object from the container. It doesn’t do any clean up, or any validation.

Putting it all together

Finally, a builder object is used to wire all that together and produce a command processor

private static IAmACommandProcessor BuildCommandProcessor(IServiceProvider serviceProvider)
{
    var registry = CreateRegistry(); // 1. Maps commands to Handlers
    var factory = new ServiceProviderHandler(serviceProvider); // 2. Builds handlers

    var builder = CommandProcessorBuilder.With()
        .Handlers(new HandlerConfiguration(
            subscriberRegistry: registry,
            handlerFactory: factory))
        .DefaultPolicy()
        .NoTaskQueues()
        .RequestContextFactory(new InMemoryRequestContextFactory());

    return builder.Build();
}

There are other things this is doing, but for the moment we’re not concerned about them.

And that’s it, the only thing left is the entry point (the Main method) of the application.

static void Main(string[] args)
{
    var serviceProvider = BuildServiceProvider();
    var commandProcessor = BuildCommandProcessor(serviceProvider);

    commandProcessor.Send(new SalutationCommand("Christian"));

    Console.ReadLine();
}

When run, it emits a single line at the console, which reads:

Greetings, Christian