Exemple #1
0
        /// <inheritdoc />
        protected override async Task <Result <StringStream, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var data = await Data.Run(stateMonad, cancellationToken);

            if (data.IsFailure)
            {
                return(data.ConvertFailure <StringStream>());
            }

            var algorithm = await Algorithm.Run(stateMonad, cancellationToken);

            if (algorithm.IsFailure)
            {
                return(algorithm.ConvertFailure <StringStream>());
            }

            var hashAlgorithm = Create(algorithm.Value);

            var hash = await hashAlgorithm.ComputeHashAsync(
                data.Value.GetStream().stream,
                cancellationToken
                );

            StringStream result = Encoding.UTF8.GetString(hash);

            hashAlgorithm.Dispose();

            return(result);
        }
Exemple #2
0
        /// <inheritdoc />
        protected override async Task <Result <Array <StringStream>, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var stringResult = await String.Run(stateMonad, cancellationToken)
                               .Map(async x => await x.GetStringAsync());

            if (stringResult.IsFailure)
            {
                return(stringResult.ConvertFailure <Array <StringStream> >());
            }

            var delimiterResult = await Delimiter.Run(stateMonad, cancellationToken)
                                  .Map(async x => await x.GetStringAsync());

            if (delimiterResult.IsFailure)
            {
                return(delimiterResult.ConvertFailure <Array <StringStream> >());
            }

            var results = stringResult.Value
                          .Split(new[] { delimiterResult.Value }, StringSplitOptions.None)
                          .Select(x => new StringStream(x) as StringStream)
                          .ToList()
                          .ToSCLArray();

            return(results);
        }
Exemple #3
0
        /// <inheritdoc />
        protected override async Task <Result <Unit, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var variable = stateMonad.GetVariable <int>(Variable).MapError(x => x.WithLocation(this));

            if (variable.IsFailure)
            {
                return(variable.ConvertFailure <Unit>());
            }

            var amount = await Amount.Run(stateMonad, cancellationToken);

            if (amount.IsFailure)
            {
                return(amount.ConvertFailure <Unit>());
            }

            var r = await stateMonad.SetVariableAsync(
                Variable,
                variable.Value + amount.Value,
                false,
                this
                );

            return(r);
        }
Exemple #4
0
        /// <inheritdoc />
        async Task <Result <T, IError> > IStep <T> .Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            using (stateMonad.Logger.BeginScope(Name))
            {
                object[] GetEnterStepArgs()
                {
                    var properties = AllProperties
                                     .ToDictionary(x => x.Name, x => x.GetLogName());

                    return(new object[] { Name, properties });
                }

                LogSituation.EnterStep.Log(stateMonad, this, GetEnterStepArgs());

                var result = await Run(stateMonad, cancellationToken);

                if (result.IsFailure)
                {
                    LogSituation.ExitStepFailure.Log(stateMonad, this, Name, result.Error.AsString);
                }
                else
                {
                    var resultValue = SerializeOutput(result.Value);

                    LogSituation.ExitStepSuccess.Log(stateMonad, this, Name, resultValue);
                }

                return(result);
Exemple #5
0
        /// <inheritdoc />
        protected override async Task <Result <Unit, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            while (true)
            {
                var conditionResult = await Condition.Run(stateMonad, cancellationToken);

                if (conditionResult.IsFailure)
                {
                    return(conditionResult.ConvertFailure <Unit>());
                }

                if (conditionResult.Value)
                {
                    var actionResult = await Action.Run(stateMonad, cancellationToken);

                    if (actionResult.IsFailure)
                    {
                        return(actionResult.ConvertFailure <Unit>());
                    }
                }
                else
                {
                    break;
                }
            }

            return(Unit.Default);
        }
Exemple #6
0
        /// <inheritdoc />
        protected override async Task <Result <bool, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var superstringResult = await String.Run(stateMonad, cancellationToken)
                                    .Map(async x => await x.GetStringAsync());

            if (superstringResult.IsFailure)
            {
                return(superstringResult.ConvertFailure <bool>());
            }

            var substringResult = await Substring.Run(stateMonad, cancellationToken)
                                  .Map(async x => await x.GetStringAsync());

            if (substringResult.IsFailure)
            {
                return(substringResult.ConvertFailure <bool>());
            }

            var ignoreCaseResult = await IgnoreCase.Run(stateMonad, cancellationToken);

            if (ignoreCaseResult.IsFailure)
            {
                return(ignoreCaseResult.ConvertFailure <bool>());
            }

            var comparison = ignoreCaseResult.Value
            ? StringComparison.OrdinalIgnoreCase
            : StringComparison.Ordinal;

            var r = superstringResult.Value.Contains(substringResult.Value, comparison);

            return(r);
        }
Exemple #7
0
 /// <inheritdoc />
 protected override async Task <Result <int, IError> > Run(
     IStateMonad stateMonad,
     CancellationToken cancellationToken)
 {
     return(await Array.Run(stateMonad, cancellationToken)
            .Bind(x => x.CountAsync(cancellationToken)));
 }
Exemple #8
0
        /// <inheritdoc />
        protected override async Task <Result <Unit, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var script = await Script.Run(stateMonad, cancellationToken).Map(x => x.GetStringAsync());

            if (script.IsFailure)
            {
                return(script.ConvertFailure <Unit>());
            }

            Entity?vars = null;

            if (Variables != null)
            {
                var variables = await Variables.Run(stateMonad, cancellationToken);

                if (variables.IsFailure)
                {
                    return(variables.ConvertFailure <Unit>());
                }

                vars = variables.Value;
            }

            await PwshRunner.RunScript(script.Value, stateMonad.Logger, vars);

            return(Unit.Default);
        }
Exemple #9
0
 /// <inheritdoc />
 protected override async Task <Result <Unit, IError> > Run(
     IStateMonad stateMonad,
     CancellationToken cancellationToken)
 {
     return(await Value.Run(stateMonad, cancellationToken)
            .Bind(x => stateMonad.SetVariableAsync(Variable, x, true, this)));
 }
Exemple #10
0
        public static TState Execute <TState, TValue>(this IStateMonad <TState, TValue> self, TState state, Action <TValue> onValue)
        {
            StateResult <TState, TValue> result = self.Run(state);

            onValue(result.Value);
            return(result.State);
        }
        /// <inheritdoc />
        protected override async Task <Result <Array <Entity>, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            await Task.CompletedTask;

            var documented = stateMonad.StepFactoryStore
                             .Dictionary
                             .GroupBy(x => x.Value, x => x.Key)
                             .Select(x => new StepWrapper(x))
                             .ToList();

            var files = DocumentationCreator.CreateDocumentation(documented);

            var entities =
                files.Select(
                    x => Entity.Create(
                        ("FileName", x.FileName),
                        ("Title", x.Title),
                        ("FileText", x.FileText),
                        ("Directory", x.Directory),
                        ("Category", x.Category)
                        )
                    )
                .ToSCLArray();

            return(entities);
        }
Exemple #12
0
        /// <inheritdoc />
        protected override async Task <Result <Unit, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var data = await Data.Run(stateMonad, cancellationToken);

            if (data.IsFailure)
            {
                return(data.ConvertFailure <Unit>());
            }

            var(stream, _) = data.Value.GetStream();

            try
            {
                await stream.CopyToAsync(
                    stateMonad.ExternalContext.Console.OpenStandardError(),
                    cancellationToken
                    );
            }
            catch (Exception e)
            {
                return(Result.Failure <Unit, IError>(
                           ErrorCode.ExternalProcessError.ToErrorBuilder(e).WithLocation(this)
                           ));
            }

            return(Unit.Default);
        }
        public async Task GetOrCreateNuixConnection_WhenScriptFileDoesNotExist_ReturnsError()
        {
            var fakeExternalProcess = new ExternalProcessMock(
                1,
                ConnectionTestsHelper.GetCreateCaseAction()
                );

            var fileMock =
                Mock.Of <IFile>(f => f.Exists(It.IsAny <string>()) == false);

            IStateMonad state = ConnectionTestsHelper.GetStateMonad(
                TestLoggerFactory.Create(),
                fakeExternalProcess,
                ConsoleAdapter.Instance
                );

            //Remove the script from the file system
            var nuixFileSystem =
                state.ExternalContext.TryGetContext <IFileSystem>(ConnectorInjection.FileSystemKey);

            nuixFileSystem.Value.File.Delete(NuixConnectionHelper.NuixGeneralScriptName);

            var connection = await state.GetOrCreateNuixConnection(null, false);

            Assert.True(connection.IsFailure);

            Assert.Matches(
                $"Could not find.+{NuixConnectionHelper.NuixGeneralScriptName}'",
                connection.Error.AsString
                );
        }
Exemple #14
0
        /// <inheritdoc />
        protected override async Task <Result <Array <Entity>, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var entityStreamResult = await EntityStream.Run(stateMonad, cancellationToken);

            if (entityStreamResult.IsFailure)
            {
                return(entityStreamResult.ConvertFailure <Array <Entity> >());
            }

            var currentState = stateMonad.GetState().ToImmutableDictionary();

            async ValueTask <Entity> Action(Entity record)
            {
                await using var scopedMonad = new ScopedStateMonad(
                                stateMonad,
                                currentState,
                                new KeyValuePair <VariableName, object>(Variable, record)
                                );

                var result = await Function.Run(scopedMonad, cancellationToken);

                if (result.IsFailure)
                {
                    throw new ErrorException(result.Error);
                }

                return(result.Value);
            }

            var newStream = entityStreamResult.Value.SelectAwait(Action);

            return(newStream);
        }
Exemple #15
0
        /// <inheritdoc />
        protected override async Task <Result <StringStream, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var index = await Index.Run(stateMonad, cancellationToken);

            if (index.IsFailure)
            {
                return(index.ConvertFailure <StringStream>());
            }

            var stringStreamResult = await String.Run(stateMonad, cancellationToken);

            if (stringStreamResult.IsFailure)
            {
                return(stringStreamResult);
            }

            var str = await stringStreamResult.Value.GetStringAsync();

            if (index.Value < 0 || index.Value >= str.Length)
            {
                return(new SingleError(new ErrorLocation(this), ErrorCode.IndexOutOfBounds));
            }

            var character = str[index.Value].ToString();

            return(new StringStream(character));
        }
Exemple #16
0
        /// <inheritdoc />
        protected override async Task <Result <T, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var arrayResult = await Array.Run(stateMonad, cancellationToken);

            if (arrayResult.IsFailure)
            {
                return(arrayResult.ConvertFailure <T>());
            }

            var indexResult = await Index.Run(stateMonad, cancellationToken);

            if (indexResult.IsFailure)
            {
                return(indexResult.ConvertFailure <T>());
            }

            var r = await arrayResult.Value.ElementAtAsync(
                indexResult.Value,
                new ErrorLocation(this),
                cancellationToken
                );

            return(r);
        }
Exemple #17
0
        /// <inheritdoc />
        protected override async Task <Result <T, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var entity = await Entity.Run(stateMonad, cancellationToken);

            if (entity.IsFailure)
            {
                return(entity.ConvertFailure <T>());
            }

            var propertyResult = await Property.Run(stateMonad, cancellationToken)
                                 .Map(x => x.GetStringAsync());

            if (propertyResult.IsFailure)
            {
                return(propertyResult.ConvertFailure <T>());
            }

            var epk = new EntityPropertyKey(propertyResult.Value);

            var entityValue = entity.Value.TryGetValue(epk);

            if (entityValue.HasNoValue)
            {
                return(EntityValue.GetDefaultValue <T>());
            }

            var result = entityValue.Value.TryGetValue <T>()
                         .MapError(x => x.WithLocation(this));

            return(result);
        }
Exemple #18
0
        /// <summary>
        /// Runs this step asynchronously.
        /// </summary>
        protected async Task <Result <T, IError> > RunAsync(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var methodParameters = await TryGetMethodParameters(stateMonad, cancellationToken);

            if (methodParameters.IsFailure)
            {
                return(methodParameters.ConvertFailure <T>());
            }

            var nuixConnection = await stateMonad.GetOrCreateNuixConnection(this, false);

            if (nuixConnection.IsFailure)
            {
                return(nuixConnection.ConvertFailure <T>().MapError(x => x.WithLocation(this)));
            }

            var runResult = await nuixConnection.Value.RunFunctionAsync(
                stateMonad,
                this,
                RubyScriptStepFactory.RubyFunction,
                methodParameters.Value,
                CasePathParameter,
                cancellationToken
                );

            if (runResult.IsFailure &&
                runResult.Error.GetErrorBuilders()
                .Any(x => x.Data is ErrorData.ExceptionData {
                Exception: ChannelClosedException
            }))
Exemple #19
0
        /// <inheritdoc />
        protected override async Task <Result <Unit, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var elements = await Array.Run(stateMonad, cancellationToken);

            if (elements.IsFailure)
            {
                return(elements.ConvertFailure <Unit>());
            }

            var currentState = stateMonad.GetState().ToImmutableDictionary();

            async ValueTask <Result <Unit, IError> > Apply(T element, CancellationToken cancellation)
            {
                var scopedMonad = new ScopedStateMonad(
                    stateMonad,
                    currentState,
                    new KeyValuePair <VariableName, object>(Variable, element !)
                    );

                var result = await Action.Run(scopedMonad, cancellation);

                return(result);
            }

            var finalResult = await elements.Value.ForEach(Apply, cancellationToken);

            return(finalResult);
        }
Exemple #20
0
        /// <inheritdoc />
        protected override async Task <Result <Array <Entity>, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var mappings = await Mappings.Run(stateMonad, cancellationToken)
                           .Map(
                e => e
                .ToDictionary(x => x.Name, x => x.BestValue.GetPrimitiveString())
                );

            if (mappings.IsFailure)
            {
                return(mappings.ConvertFailure <Array <Entity> >());
            }

            var entityStream = await EntityStream.Run(stateMonad, cancellationToken);

            if (entityStream.IsFailure)
            {
                return(entityStream.ConvertFailure <Array <Entity> >());
            }

            var newEntityStream = entityStream.Value
                                  .Select(e => ChangeHeader(e, mappings.Value));

            return(newEntityStream);
Exemple #21
0
        /// <inheritdoc />
        protected override async Task <Result <Unit, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var left = await Left.Run(stateMonad, cancellationToken);

            if (left.IsFailure)
            {
                return(left.ConvertFailure <Unit>());
            }

            var right = await Right.Run(stateMonad, cancellationToken);

            if (right.IsFailure)
            {
                return(right.ConvertFailure <Unit>());
            }

            var r = left.Value is not null && left.Value.Equals(right.Value);

            if (r)
            {
                return(Unit.Default);
            }

            var lString = await SerializationMethods.GetStringAsync(left.Value);

            var rString = await SerializationMethods.GetStringAsync(right.Value);

            var error = ErrorCode.AssertionFailed
                        .ToErrorBuilder($"Expected {lString} to equal {rString}")
                        .WithLocation(this);

            return(Result.Failure <Unit, IError>(error));
        }
Exemple #22
0
        /// <inheritdoc />
        protected override async Task <Result <Entity, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var entityResult = await Entity.Run(stateMonad, cancellationToken);

            if (entityResult.IsFailure)
            {
                return(entityResult);
            }

            var propertyResult = await Property.Run(stateMonad, cancellationToken);

            if (propertyResult.IsFailure)
            {
                return(propertyResult.ConvertFailure <Entity>());
            }

            var valueResult = await Value.Run(stateMonad, cancellationToken)
                              .Bind(x => EntityHelper.TryUnpackObjectAsync(x, cancellationToken));

            if (valueResult.IsFailure)
            {
                return(valueResult.ConvertFailure <Entity>());
            }

            var propertyName = await propertyResult.Value.GetStringAsync();

            var entityValue = EntityValue.CreateFromObject(valueResult.Value);

            var newEntity = entityResult.Value.WithProperty(propertyName, entityValue);

            return(newEntity);
        }
Exemple #23
0
            /// <inheritdoc />
            protected override async Task <Result <int, IError> > Run(
                IStateMonad stateMonad,
                CancellationToken cancellationToken)
            {
                await Task.CompletedTask;

                return(1);
            }
Exemple #24
0
        /// <inheritdoc />
        protected override async Task <Result <Unit, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var pathResult = await Path.Run(stateMonad, cancellationToken)
                             .Map(async x => await x.GetStringAsync());

            if (pathResult.IsFailure)
            {
                return(pathResult.ConvertFailure <Unit>());
            }

            List <string> arguments;

            if (Arguments == null)
            {
                arguments = new List <string>();
            }
            else
            {
                var argsResult = await Arguments.Run(stateMonad, cancellationToken)
                                 .Bind(x => x.GetElementsAsync(cancellationToken));

                if (argsResult.IsFailure)
                {
                    return(argsResult.ConvertFailure <Unit>());
                }

                arguments = new List <string>();

                foreach (var stringStream in argsResult.Value)
                {
                    arguments.Add(await stringStream.GetStringAsync());
                }
            }

            var encodingResult = await Encoding.Run(stateMonad, cancellationToken);

            if (encodingResult.IsFailure)
            {
                return(encodingResult.ConvertFailure <Unit>());
            }

            var r = await
                    stateMonad.ExternalContext.ExternalProcessRunner.RunExternalProcess(
                pathResult.Value,
                IgnoreNoneErrorHandler.Instance,
                arguments,
                new Dictionary <string, string>(),    //TODO let user control this
                encodingResult.Value.Convert(),
                stateMonad,
                this,
                cancellationToken
                )
                    .MapError(x => x.WithLocation(this));

            return(r);
        }
Exemple #25
0
 /// <summary>
 /// Create a new ScopedStateMonad
 /// </summary>
 public ScopedStateMonad(
     IStateMonad baseStateMonad,
     ImmutableDictionary <VariableName, object> fixedState,
     params KeyValuePair <VariableName, object>[] state)
 {
     _fixedState            = fixedState;
     BaseStateMonad         = baseStateMonad;
     _scopedStateDictionary = new ConcurrentDictionary <VariableName, object>(state);
 }
Exemple #26
0
        /// <inheritdoc />
        protected override async Task <Result <Entity, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            await Task.CompletedTask;
            var entity = stateMonad.Settings.Entity;

            return(entity);
        }
Exemple #27
0
        /// <inheritdoc />
        protected override async Task <Result <Array <Entity>, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var script = await Script.Run(stateMonad, cancellationToken).Map(x => x.GetStringAsync());

            if (script.IsFailure)
            {
                return(script.ConvertFailure <Array <Entity> >());
            }

            Entity?vars = null;

            if (Variables != null)
            {
                var variables = await Variables.Run(stateMonad, cancellationToken);

                if (variables.IsFailure)
                {
                    return(variables.ConvertFailure <Array <Entity> >());
                }

                vars = variables.Value;
            }

            PSDataCollection <PSObject>?input = null;

        #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
            async ValueTask <Result <Unit, IError> > AddObject(Entity x, CancellationToken ct)
            {
                input.Add(PwshRunner.PSObjectFromEntity(x));
                return(Unit.Default);
            }

        #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously

            if (Input != null)
            {
                var inputStream = await Input.Run(stateMonad, cancellationToken);

                if (inputStream.IsFailure)
                {
                    return(inputStream.ConvertFailure <Array <Entity> >());
                }

                input = new PSDataCollection <PSObject>();

                _ = inputStream.Value.ForEach(AddObject, cancellationToken)
                    .ContinueWith(_ => input.Complete(), cancellationToken);
            }

            var stream = PwshRunner.GetEntityEnumerable(script.Value, stateMonad.Logger, vars, input)
                         .ToSCLArray();

            return(stream);
        }
Exemple #28
0
        /// <inheritdoc />
        protected override async Task <Result <Unit, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            await Task.CompletedTask;

            var r = await stateMonad.CloseNuixConnectionAsync(this, cancellationToken);

            return(r.MapError(x => x.WithLocation(this)));
        }
Exemple #29
0
        /// <inheritdoc />
        protected override async Task <Result <Array <T>, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var result = await Elements.Select(x => x.Run(stateMonad, cancellationToken))
                         .Combine(ErrorList.Combine)
                         .Map(x => x.ToList().ToSCLArray());

            return(result);
        }
Exemple #30
0
        /// <inheritdoc />
        protected override async Task <Result <Array <T>, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var entityStreamResult = await Array.Run(stateMonad, cancellationToken);

            if (entityStreamResult.IsFailure)
            {
                return(entityStreamResult.ConvertFailure <Array <T> >());
            }

            var ignoreCaseResult = await IgnoreCase.Run(stateMonad, cancellationToken);

            if (ignoreCaseResult.IsFailure)
            {
                return(ignoreCaseResult.ConvertFailure <Array <T> >());
            }

            IEqualityComparer <string> comparer = ignoreCaseResult.Value
            ? StringComparer.OrdinalIgnoreCase
            : StringComparer.Ordinal;

            HashSet <string> usedKeys = new(comparer);

            var currentState = stateMonad.GetState().ToImmutableDictionary();

            async IAsyncEnumerable <T> Filter(T element)
            {
                await using var scopedMonad = new ScopedStateMonad(
                                stateMonad,
                                currentState,
                                new KeyValuePair <VariableName, object>(Variable, element !)
                                );

                var result = await KeySelector.Run(scopedMonad, cancellationToken)
                             .Map(async x => await x.GetStringAsync());

                if (result.IsFailure)
                {
                    throw new ErrorException(result.Error);
                }

                if (usedKeys.Add(result.Value))
                {
                    yield return(element);
                }
            }

            var newStream = entityStreamResult.Value.SelectMany(Filter);

            return(newStream);
        }