Beispiel #1
0
 public ScanResult ScanBuffer(byte[] buffer, uint length, string contentName)
 {
     using (var resultBuilder = new ResultBuilder(
                new ScanContext(
                    client
                    , sessionHandle
                    , contentName
                    , ContentType.ByteArray
                    , FileType.Unknown
                    , buffer.LongLength
                    , client.Configuration.SkipContentHashing ? null : buffer.GetMD5Hash())))
     {
         var result = AMSIMethods.AmsiScanBuffer(
             client.ContextHandle
             , buffer
             , length
             , contentName
             , sessionHandle
             , out var resultNumber);
         ScanResult scanResult = null;
         result.CheckResult(
             success: _ => scanResult   = resultBuilder.ToResult(resultNumber)
             , failure: _ => scanResult = resultBuilder.ToResult(new Win32Exception(result)));
         return(scanResult);
     }
 }
        private Result ProcessCache(CacheMessage message)
        {
            try
            {
                if (message == null)
                {
                    return(ResultBuilder.Warning("Mensagem inválida."));
                }

                MessageLogger.Received(message);

                //var cacher = Cachers.Actual[message.ContentType];

                //if (cacher == null) return ResultBuilder.Warning($"{message.ContentType}: Cacher não encontrado.");

                //cacher.StoreCache(message);

                ResultBuilder.Warning($"{message.ContentType}: Cacher não encontrado.");

                MessageLogger.Consumed(message);

                return(ResultBuilder.Success());
            }
            catch (Exception)
            {
                MessageLogger.Error(message);
                throw;
            }
        }
Beispiel #3
0
 public ScanResult ScanString(string content, string contentName)
 {
     using (var resultBuilder = new ResultBuilder(
                new ScanContext(
                    client
                    , sessionHandle
                    , contentName
                    , ContentType.String
                    , FileType.Unknown
                    , content.Length * 4
                    , client.Configuration.SkipContentHashing ? null : content.GetMD5Hash())))
     {
         var result = AMSIMethods.AmsiScanString(
             client.ContextHandle
             , content
             , contentName
             , sessionHandle
             , out var resultNumber);
         ScanResult scanResult = null;
         result.CheckResult(
             success: _ => scanResult   = resultBuilder.ToResult(resultNumber)
             , failure: _ => scanResult = resultBuilder.ToResult(new Win32Exception(result)));
         return(scanResult);
     }
 }
Beispiel #4
0
        public void BuildCommonResponse_Result_ShouldSerializeToJson_Successfully()
        {
            IResult <string> response = new ResultBuilder <string>().WithData(Result).Build();
            string           json     = JsonConvert.SerializeObject(response);

            Assert.NotEqual(string.Empty, json);
        }
Beispiel #5
0
        public void BuildCommonResponse_Result_ShouldContainOnlyResult()
        {
            IResult <string> response = new ResultBuilder <string>().WithData(Result).Build();

            Assert.True(response.HasData());
            Assert.False(response.HasErrors());
        }
Beispiel #6
0
        public void Notified(Func <NotifyResult, NotifyReturnMessage> onNotified)
        {
            var request = HttpContext.Current.Request;
            var respose = HttpContext.Current.Response;

            respose.ContentType = "text/plain";
            Dictionary <string, string> dictToReturn = new Dictionary <string, string>();

            dictToReturn.Add("return_code", "SUCCESS");
            dictToReturn.Add("return_msg", "");
            NotifyResult result = null;
            string       xml;

            xml = GetResultXml(request);
            ResultBuilder resultBuilder = new ResultBuilder(xml);

            resultBuilder.BasicValidate();
            result = new NotifyResult(resultBuilder);

            NotifyReturnMessage returnMessage = onNotified(result);

            if (!returnMessage.Success)
            {
                dictToReturn["return_code"] = "FAIL";
                dictToReturn["return_msg"]  = returnMessage.Message;
            }
            respose.Write(CommonHelper.CreateXmlForReturn(dictToReturn));
        }
        private async Task RunAsync()
        {
            var modelConfig       = ModelConfig.Value;
            var cancellationToken = Lifetime.ApplicationStopped;

            var loading = new GraphLoading(modelConfig.ModelToUse);
            var catalog = new Catalog(modelConfig.LabelsToUse);
            await catalog.LoadAsync(cancellationToken);

            using (var resultBuilder = new ResultBuilder(modelConfig.OutputFileName, catalog))
                using (var graph = await loading.LoadGraphAsync(cancellationToken))
                    using (var session = new TFSession(graph))
                    {
                        var batch = new List <string>(modelConfig.BatchSize);

                        foreach (var imageDirectory in modelConfig.ImageDirectories)
                        {
                            foreach (var inputFile in Directory.EnumerateFiles(imageDirectory, "*.jpg", SearchOption.AllDirectories))
                            {
                                cancellationToken.ThrowIfCancellationRequested();
                                batch.Add(Path.Combine(imageDirectory, inputFile));
                                if (batch.Count == batch.Capacity)
                                {
                                    await ProcessBatch(resultBuilder, graph, session, batch, cancellationToken);

                                    batch.Clear();
                                }
                            }
                        }
                    }
            Logger.LogInformation("All images processed");
            Lifetime.StopApplication();
        }
Beispiel #8
0
        public CommandResult ProcessCommand(string commands)
        {
            ICommandInput cmd = CommandBuilder.GetCommandInput(commands);

            if (cmd.CommandName == CommandNames.Add)
            {
                return(DomainRouter.AddCommand(cmd));
            }
            if (cmd.CommandName == CommandNames.Delete)
            {
                return(DomainRouter.DeleteCommand(cmd));
            }
            if (cmd.CommandName == CommandNames.View)
            {
                return(DomainRouter.GetCommand(cmd));
            }
            if (cmd.CommandName == CommandNames.Update)
            {
                return(DomainRouter.UpdateCommand(cmd));
            }
            if (cmd.CommandName == CommandNames.Help)
            {
                return(DomainRouter.HelpCommand(cmd));
            }
            else
            {
                return(ResultBuilder.Build(cmd, "Unable To Find Command", false, null));
            }
        }
                public void ShouldUseDefaultValuesWhenPlanIsThereButHasNoData()
                {
                    var builder = new ResultBuilder();
                    var meta    = new Dictionary <string, object>
                    {
                        {
                            "plan", new Dictionary <string, object>
                            {
                                { "operatorType", "opType" }
                            }
                        }
                    };

                    builder.CollectSummary(meta);
                    var actual = builder.PreBuild();

                    actual.Consume();

                    actual.Summary.Plan.Should().NotBeNull();
                    actual.Summary.HasPlan.Should().BeTrue();

                    var plan = actual.Summary.Plan;

                    plan.Arguments.Should().BeEmpty();

                    plan.OperatorType.Should().Be("opType");
                    plan.Identifiers.Should().BeEmpty();
                    plan.Children.Should().BeEmpty();
                }
                public void ShouldUseDefaultValuesWhenProfileIsThereButHasNoData()
                {
                    var builder = new ResultBuilder();
                    var meta    = new Dictionary <string, object>
                    {
                        {
                            "profile", new Dictionary <string, object>
                            {
                                { "operatorType", "opType" },
                                { "rows", 1L },
                                { "dbHits", 2L },
                            }
                        }
                    };

                    builder.CollectSummary(meta);
                    var actual = builder.PreBuild();

                    actual.Consume();

                    actual.Summary.Profile.Should().NotBeNull();
                    actual.Summary.HasProfile.Should().BeTrue();

                    var profile = actual.Summary.Profile;

                    profile.Arguments.Should().BeEmpty();

                    profile.OperatorType.Should().Be("opType");
                    profile.Identifiers.Should().BeEmpty();
                    profile.Children.Should().BeEmpty();

                    profile.Records.Should().Be(1L);
                    profile.DbHits.Should().Be(2L);
                }
Beispiel #11
0
        protected override Result Apply(ref GoFishGame game)
        {
            var resultBuilder = new ResultBuilder();

            switch (game.GameState)
            {
            case GameState.Waiting:
                game.Players.Remove(_player);
                resultBuilder.AddFeedback($"{_player.Username} left the game.");
                break;

            case GameState.Playing:
                Player gameplayer = game.Players.First(p => p.Equals(_player));
                foreach (Card card in gameplayer.Cards.Concat(gameplayer.FinishedCollections.SelectMany(c => c.Value)))
                {
                    game.Deck.InsertAt(game.Deck.Count - 1, card);
                }
                game.Deck.Shuffle();
                game.Players.Remove(gameplayer);
                resultBuilder.AddFeedback($"{_player.Username} left the game.");
                break;

            case GameState.Finished:
                break;

            default:
                throw new Exception("The given option for GameState is unknown.");
            }

            return(resultBuilder.Build());
        }
            public void ShouldPassDefaultKeysToResultIfNoKeySet()
            {
                var builder = new ResultBuilder();
                var result  = builder.PreBuild();

                result.Keys.Should().BeEmpty();
            }
Beispiel #13
0
        public void FlushBuilder()
        {
            if (builder == null)
            {
                return;
            }
            try
            {
                if (VRMain.Instance.vrDevice.name == "Desktop" || VRMain.Instance.vrDevice.name == "CaveFrontWall_Top")
                {
                    var path = Testing.Utils.WriteTrialResults(builder.Finish(currentOutput), locally: Application.isEditor);

                    fileOutputIndicator.text += $"Trial {trialNumber} Completed!\nSaved in Directory: {path.directory}\nIn File: {path.name}\n";
                }
            }
            catch (Exception e)
            {
                Debug.LogException(e);

                fileOutputIndicator.text += $"Trial {trialNumber} completed!\nSaving Failed with: {e.Message}";
            }
            finally
            {
                currentTrial = null;
                builder      = null;
            }
        }
Beispiel #14
0
        protected override Result Apply(ref GoFishGame game)
        {
            ResultBuilder resultBuilder = new ResultBuilder();

            if (game.Deck.TryDraw(out Card card))
            {
                game.CurrentPlayer.Cards.Add(card);
                resultBuilder.AddFeedback($"{game.CurrentPlayer.Username} drew a card from the deck.");


                string      collection          = card.Collection;
                ISet <Card> cardsFromCollection = new HashSet <Card>(game.CurrentPlayer.Cards.Where(c => c.Collection.Equals(collection)));
                if (cardsFromCollection.Count >= 4)
                {
                    game.CurrentPlayer.FinishedCollections.Add(collection, cardsFromCollection);
                    game.CurrentPlayer.Cards.ExceptWith(cardsFromCollection);
                    resultBuilder.AddFeedback($"{game.CurrentPlayer.Username} finished the {collection} collection!");
                }
            }

            game.CurrentPlayer = _to;
            resultBuilder.AddFeedback($"The turn was passed to {game.CurrentPlayer.Username}");

            return(resultBuilder.Build());
        }
Beispiel #15
0
        public void BuildCommonResponse_Error_ShouldSerializeToJsonSuccessfully()
        {
            IResult <string> error = new ResultBuilder <string>().WithError(builder => builder.WithMessage(Error).Build()).Build();
            string           json  = JsonConvert.SerializeObject(error);

            Assert.NotEqual(string.Empty, json);
        }
Beispiel #16
0
 public void RunTrial(Trial t)
 {
     currentTrial    = t;
     _challengeIndex = -1;
     builder         = new ResultBuilder();
     AdvanceChallenge();
 }
Beispiel #17
0
        protected override Expression VisitMember(MemberExpression expression)
        {
            // Field hierarchy is flattened (Person.Address.Street is just Street), append as is, do not call Visit.

            // Property call (string.Length, DateTime.Month, etc).
            if (MethodVisitor.VisitPropertyCall(expression, this))
            {
                return(expression);
            }

            // Special case: grouping
            if (VisitGroupByMember(expression.Expression))
            {
                return(expression);
            }

            var queryable = ExpressionWalker.GetCacheQueryable(expression, false);

            if (queryable != null)
            {
                var fieldName = GetEscapedFieldName(expression, queryable);

                ResultBuilder.AppendFormat("{0}.{1}", Aliases.GetTableAlias(expression), fieldName);
            }
            else
            {
                AppendParameter(ExpressionWalker.EvaluateExpression <object>(expression));
            }

            return(expression);
        }
Beispiel #18
0
        protected override Expression VisitUnary(UnaryExpression expression)
        {
            var closeBracket = false;

            switch (expression.NodeType)
            {
            case ExpressionType.Negate:
                ResultBuilder.Append("(");
                ResultBuilder.Append("-");
                closeBracket = true;
                break;

            case ExpressionType.Not:
                ResultBuilder.Append("(");
                ResultBuilder.Append("not ");
                closeBracket = true;
                break;

            case ExpressionType.Convert:
                // Ignore, let the db do the conversion
                break;

            default:
                return(base.VisitUnary(expression));
            }

            Visit(expression.Operand);

            if (closeBracket)
            {
                ResultBuilder.Append(")");
            }

            return(expression);
        }
Beispiel #19
0
        protected override Expression VisitSubQuery(SubQueryExpression expression)
        {
            var subQueryModel = expression.QueryModel;

            var contains = subQueryModel.ResultOperators.FirstOrDefault() as ContainsResultOperator;

            // Check if IEnumerable.Contains is used.
            if (subQueryModel.ResultOperators.Count == 1 && contains != null)
            {
                VisitContains(subQueryModel, contains);
            }
            else if (_visitEntireSubQueryModel)
            {
                ResultBuilder.Append("(");
                _modelVisitor.VisitQueryModel(subQueryModel, false, true);
                ResultBuilder.Append(")");
            }
            else
            {
                // This happens when New expression uses a subquery, in a GroupBy.
                _modelVisitor.VisitSelectors(expression.QueryModel, false);
            }

            return(expression);
        }
Beispiel #20
0
        /** <inheritdoc /> */
        protected override Expression VisitQuerySourceReference(QuerySourceReferenceExpression expression)
        {
            // In some cases of Join clause different handling should be introduced
            var joinClause = expression.ReferencedQuerySource as JoinClause;

            if (joinClause != null && ExpressionWalker.GetCacheQueryable(expression, false) == null)
            {
                var tableName = Aliases.GetTableAlias(expression);
                var fieldname = Aliases.GetFieldAlias(expression);

                ResultBuilder.AppendFormat("{0}.{1}", tableName, fieldname);
            }
            else if (joinClause != null && joinClause.InnerSequence is SubQueryExpression)
            {
                var subQueryExpression = (SubQueryExpression)joinClause.InnerSequence;
                base.Visit(subQueryExpression.QueryModel.SelectClause.Selector);
            }
            else
            {
                // Count, sum, max, min expect a single field or *
                // In other cases we need both parts of cache entry
                var format = _includeAllFields
                    ? "{0}.*, {0}._KEY, {0}._VAL"
                    : _useStar
                        ? "{0}.*"
                        : "{0}._KEY, {0}._VAL";

                var tableName = Aliases.GetTableAlias(expression);

                ResultBuilder.AppendFormat(format, tableName);
            }

            return(expression);
        }
        public Route GetResult()
        {
            var route = new ResultBuilder(solverData).CreateResult();

            route.SolutionValue = SolutionValue();
            return(route);
        }
    public static void SendStatementWithResult(string verb, string activityType, string activityName, Dictionary <string, string> activityExtensions = null, Dictionary <string, string> resultExtensions = null, bool?completed = null, bool?success = null, string response = null, int?score = null,
                                               float duration = 0)
    {
        ActivityDefinitionBuilder.IOptional definitionBuilder = GBLXAPI.ActivityDefinition
                                                                .WithType(activityType)
                                                                .WithName(activityName);
        if (activityExtensions != null)
        {
            //set extensions
            ExtensionsBuilder extensions = GBLXAPI.Extensions;
            foreach (KeyValuePair <string, string> entry in activityExtensions)
            {
                extensions = extensions.WithStandard(entry.Key, entry.Value);
            }
            definitionBuilder.WithExtensions(extensions.Build());
        }

        ResultBuilder resultBuilder = GBLXAPI.Result;

        if (completed != null)
        {
            resultBuilder = resultBuilder.WithCompletion(completed == true);
        }
        if (success != null)
        {
            resultBuilder = resultBuilder.WithSuccess(success == true);
        }
        if (score != null)
        {
            resultBuilder = resultBuilder.WithScore(score);
        }
        if (response != null)
        {
            resultBuilder = resultBuilder.WithResponse(response);
        }
        if (resultExtensions != null)
        {
            //set extensions
            ExtensionsBuilder extensions = GBLXAPI.Extensions;
            foreach (KeyValuePair <string, string> entry in resultExtensions)
            {
                extensions = extensions.WithStandard(entry.Key, entry.Value);
            }
            resultBuilder.WithExtensions(extensions.Build());
        }

        GBLXAPI.Statement
        .WithActor(GBLXAPI.Agent
                   .WithAccount(userUUID, "https://www.lip6.fr/mocah/")
                   .WithName(playerName)
                   .Build())
        .WithVerb(verb)
        .WithTargetActivity(GBLXAPI.Activity
                            .WithID("https://www.lip6.fr/mocah/invalidURI/" + activityType + "/" + activityName)
                            .WithDefinition(definitionBuilder.Build())
                            .Build())
        .WithResult(resultBuilder)
        .Enqueue();
    }
Beispiel #23
0
        public override Result Validate(GoFishGame game)
        {
            if (game is null)
            {
                throw new ArgumentNullException(nameof(game));
            }

            ResultBuilder resultBuilder = new ResultBuilder();

            // cannot pass the turn if the game is not running
            if (game.GameState != GameState.Playing)
            {
                resultBuilder.AddFeedback("Turns can only be passed of the game is in the 'playing' state.", false);
            }

            // cannot pass the turn if you are not the current player
            if (!_from.Equals(game.CurrentPlayer))
            {
                resultBuilder.AddFeedback($"{_from.Username} cannot pass the turn because it's not their turn.", false);
            }

            // can only pass the turn according to the rules
            switch (game.RuleSet.TurnBehaviour)
            {
            case TurnBehaviour.ClockWise:

                // can not pass the turn to a player that is not the next
                if (!_to.Equals(game.NextPlayer))
                {
                    resultBuilder.AddFeedback($"The turn cannot be passed to {_to.Username}, because they're not the next clockwise player.", false);
                }
                break;

            case TurnBehaviour.LastAskedPlayer:
                // cannot pass the turn to somebody who is not in the game
                if (!game.Players.Contains(_to))
                {
                    resultBuilder.AddFeedback("The turn can only be passed to a player that actually participates in this game.", false);
                }

                // cannot pass the turn to yourself
                if (_to.Equals(_from))
                {
                    resultBuilder.AddFeedback("The turn must be passed to a different player.", false);
                }

                // cannot pass the turn to somebody who has no cards
                if (_to.Cards.Count == 0)
                {
                    resultBuilder.AddFeedback("The turn cannot be passed to a player who has no cards.", false);
                }
                break;

            default:
                throw new Exception("The given option for TurnBehaviour is unknown.");
            }

            return(resultBuilder.Build());
        }
Beispiel #24
0
        public override Result Validate(GoFishGame game)
        {
            if (game is null)
            {
                throw new ArgumentNullException(nameof(game));
            }

            ResultBuilder resultBuilder = new ResultBuilder();

            // You can only give cards when the game is running
            if (game.GameState != GameState.Playing)
            {
                resultBuilder.AddFeedback("Cards can only be given when the game is in the 'playing' state.", false);
            }

            // You can only give cards if it is not your turn
            if (_player.Equals(game.CurrentPlayer))
            {
                resultBuilder.AddFeedback($"{_player.Username} cannot give any cards away because it's their turn to ask.", false);
            }

            // You can only give cards that you have
            if (!_cards.IsSubsetOf(_player.Cards))
            {
                resultBuilder.AddFeedback($"{_player.Username} cannot give away these cards, because one or more are not in their possession.", false);
            }

            // You can only give cards according to the card giving rule
            switch (game.RuleSet.GiveCardBehaviour)
            {
            case GiveCardBehaviour.AllOfCollection:
                string collection = _cards.First().Collection;

                // Cards must all be from the same collection
                if (!_cards.All(c => c.Collection.Equals(collection)))
                {
                    resultBuilder.AddFeedback($"Only cards from the same collection can be given away at once.", false);
                }

                // All cards of the same collection must be given
                if (_player.Cards.Any(c => c.Collection.Equals(collection) && !_cards.Contains(c)))
                {
                    resultBuilder.AddFeedback($"All cards from the same collection must be given away at once.", false);
                }
                break;

            case GiveCardBehaviour.Single:
                if (_cards.Count != 1)
                {
                    resultBuilder.AddFeedback($"Only 1 card can be given away at once.", false);
                }
                break;

            default:
                throw new Exception("The given option for GiveCardBehaviour is unknown.");
            }

            return(resultBuilder.Build());
        }
        public void WithMessages_ExpectResultToHaveSuppliedMessages()
        {
            var result = ResultBuilder <int, string> .Failure()
                         .WithMessages(new[] { "Message1", "Message2", "Message3" })
                         .Build();

            Assert.AreEqual("Message1\r\nMessage2\r\nMessage3", result.ToString());
        }
        public void WithMessage_ExpectResultToHaveSuppliedMessage()
        {
            var result = ResultBuilder <int, string> .Failure()
                         .WithMessage("This is a message")
                         .Build();

            Assert.AreEqual("This is a message", result.ToString());
        }
        public void WithValue_ExpectResultToHaveSuppliedValue()
        {
            var result = ResultBuilder <int, string> .Failure()
                         .WithValue(123)
                         .Build();

            Assert.AreEqual(123, result.Value);
        }
Beispiel #28
0
        protected ResultBuilder PostForResult(string url, bool isCertificate, int timeOut = 10)
        {
            string        xml           = ParamBuilder.ToXml();
            string        resultXml     = PostToUrl(xml, url, false, timeOut);
            ResultBuilder resultBuilder = new ResultBuilder(resultXml);

            return(resultBuilder);
        }
        protected override Result ValidateMessage(IntegracaoSapBrfMessage message)
        {
            //if (Guid.Empty.Equals(message.IdTransporteParada)) return ResultBuilder.Warning(ValidationMessages.ParadaNaoInformada);

            //if (string.IsNullOrEmpty(message.EventName)) return ResultBuilder.Warning(ValidationMessages.OperacaoInvalida);

            return(ResultBuilder.Success());
        }
        private static async Task Write(HttpContext context, string message, IEnumerable <FieldError> errors = null)
        {
            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = StatusCodes.Status400BadRequest;

            var error = ResultBuilder.Error <object>(message, errors);

            await context.Response.WriteAsync(JsonConvert.SerializeObject(error, _settings));
        }