public async Task <HandlerResult> Handler(string payload, string name, string id, string userAgent, string signature)
        {
            var result = new HandlerResult();

            result.SignatureCheck = _githubWebhookHandlerSettings.CheckSignature;

            if (_githubWebhookHandlerSettings.CheckSignature && !CheckSignature(payload, signature))
            {
                result.AddErrorMessage("secret validation failed");

                return(result);
            }

            //if (hook == null)
            //{
            //    result.AddErrorMessage("deserialization failed");

            //    return result;
            //}

            var headers = CreateHeaders(id, name, userAgent, signature);

            await EventDistribution(headers, payload);

            return(result);
        }
Example #2
0
 public ActionResult Create(RssSource rssSource)
 {
     if (ControllerContext.HttpContext.Request.IsAjaxRequest())
     {
         if (ModelState.IsValid)
         {
             repository.Add(rssSource);
             var result = new HandlerResult {
                 IsSuccess = true, Message = "添加RSS源成功"
             };
             return(Json(result));
         }
         else
         {
             var result = new HandlerResult {
                 IsSuccess = false, Message = "添加RSS源失败"
             };
             return(Json(result));
         }
     }
     else
     {
         if (ModelState.IsValid)
         {
             var flag = repository.Add(rssSource);
             return(Redirect("Index"));
         }
         else
         {
             return(View(rssSource));
         }
     }
 }
Example #3
0
 public HandlerResult Handle(RoomState state, ICommand command, IRepository <IDbProperties> repository)
 {
     switch (command)
     {
     default: return(HandlerResult.NotHandled(command, command.Commander, command.CommandId));
     }
 }
Example #4
0
        protected HttpResponseMessage ProcessResultResponse(HandlerResult result)
        {
            var response = new HttpResponseMessage(result.StatusCode);

            if (!String.IsNullOrWhiteSpace(result.ReasonPhrase))
            {
                response.ReasonPhrase = result.ReasonPhrase;
            }
            if (result.Headers != null)
            {
                foreach (var header in result.Headers)
                {
                    response.Headers.TryAddWithoutValidation(header.Key, header);
                }
            }
            if (result.ErrorInformation != null && !String.IsNullOrWhiteSpace(result.ErrorInformation.ErrorCode))
            {
                var error = new HttpError
                {
                    { "Code", result.ErrorInformation.ErrorCode },
                    { "Message", result.ErrorInformation.ErrorMessage },
                };
                foreach (var msg in result.ErrorInformation.AdditionalDetails)
                {
                    error.Add(msg.Key, msg.Value);
                }
                response.Content = new ObjectContent <HttpError>(error, GlobalConfiguration.Configuration.Formatters.XmlFormatter, "application/xml");
            }
            return(response);
        }
Example #5
0
    protected override bool TryCreateViewer(FileInfo fileInfo, out HandlerResult?handlerResult)
    {
        if (!TryGetImageSize(fileInfo, out var imageSize))
        {
            handlerResult = default;

            return(false);
        }

        var requestSize = imageSize.FitTo(1200);

        var bitmap = LoadImage(fileInfo, requestSize);

        var image = new Image();

        using (image.Initialize())
        {
            image.Stretch          = Stretch.Uniform;
            image.StretchDirection = StretchDirection.DownOnly;
            image.Source           = bitmap;
        }

        handlerResult = new HandlerResult {
            Viewer = image, RequestSize = requestSize
        };

        return(true);
    }
Example #6
0
        public ActionResult Write(Article article)
        {
            var a = TryValidateModel(article);

            NLog.LogManager.GetCurrentClassLogger().Debug("是否通过====" + a);

            if (ModelState.IsValid)
            {
                article.PubDate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                var           flag   = repository.Add(article);
                HandlerResult result = null;
                if (flag)
                {
                    result = new HandlerResult {
                        IsSuccess = true, Message = "操作成功"
                    };
                }
                else
                {
                    result = new HandlerResult {
                        IsSuccess = false, Message = "操作失败"
                    };
                }
                return(View("Index"));
            }
            return(View(article));
        }
        public async Task AlwaysReThrowResult()
        {
            ReThrowExceptionHandler handler = new ReThrowExceptionHandler();
            HandlerResult           result  = await handler.Handle(null, null);

            Assert.Equal(HandlerResult.ReThrow, result);
        }
Example #8
0
        protected override void NotifyUI(ICommand command, HandlerResult result)
        {
            var mEvent = new MassTransitEvent(command.Commander, command.CommandId, result);

            PustToUIQueue(mEvent, command.ReplyToQueue);
            base.NotifyUI(command, result);
        }
Example #9
0
        public async Task <HandlerResult> Handler(string payload, string name, string id, string userAgent, string signature)
        {
            if (string.IsNullOrWhiteSpace(payload))
            {
                throw new ArgumentException($"'{nameof(payload)}' cannot be null or whitespace.", nameof(payload));
            }

            var result = new HandlerResult();

            result.SignatureCheck = _githubWebhookHandlerSettings.CheckSignature;

            if (_githubWebhookHandlerSettings.CheckSignature && !CheckSignature(payload, signature))
            {
                result.AddErrorMessage("secret validation failed");

                return(result);
            }

            //if (hook == null)
            //{
            //    result.AddErrorMessage("deserialization failed");

            //    return result;
            //}

            var headers = CreateHeaders(id, name, userAgent, signature);

            await EventDistribution(headers, payload);

            return(result);
        }
        public async Task AlwaysHandledResult()
        {
            MarkHandledHandler handler = new MarkHandledHandler();
            HandlerResult      result  = await handler.Handle(null, null);

            Assert.Equal(HandlerResult.Handled, result);
        }
Example #11
0
        public async Task AlwaysNextChainResult()
        {
            NextChainHandler handler = new NextChainHandler();
            HandlerResult    result  = await handler.Handle(null, null);

            Assert.Equal(HandlerResult.NextChain, result);
        }
Example #12
0
        public async Task <HandlerResult <Book> > Handle(CreateNewBookCommand request, CancellationToken cancellationToken)
        {
            var handlerResult = new HandlerResult <Book>();


            try
            {
                var book = new Book
                {
                    Id    = request.Id,
                    Title = request.Title,
                    Year  = request.Year
                };

                var result = await _repository.Create(book);

                if (result)
                {
                    handlerResult.Data = book;

                    return(handlerResult);
                }
            }
            catch (Exception e)
            {
                handlerResult.AddError(e.Message);
            }

            return(handlerResult);
        }
Example #13
0
        public override string GetUserOperationLog(bool iserror, LogLevel level, HandlerResult result, WebContext context)
        {
            var info = result.Data as LogonInfo;

            if (iserror)
            {
                return(new {
                    auth = false,
                    login = info.Identity.Name,
                    error = info.Identity.Error,
                    addr = info.RemoteEndPoint.Address.ToString(),
                    local = info.LocalEndPoint.Address.ToString(),
                    port = info.LocalEndPoint.Port
                }.stringify());
            }
            return(new {
                auth = true,
                type = info.Identity.AuthenticationType,
                isadmin = info.Identity.IsAdmin,
                login = info.Identity.Name,
                error = info.Identity.Error,
                addr = info.RemoteEndPoint.Address.ToString(),
                local = info.LocalEndPoint.Address.ToString(),
                port = info.LocalEndPoint.Port,
                agent = info.UserAgent
            }.stringify());
        }
Example #14
0
 /// <summary>
 /// Generic function to redirect a put request for properties of a blob
 /// </summary>
 public static async Task <HandlerResult> BasicBlobAsync(IHttpRequestWrapper requestWrapper, string container, string blob, bool servePrimaryOnly, bool operationCanReplicateBlob)
 {
     return(await WebOperationRunner.DoHandlerAsync("BlobHandler.BasicBlobAsync", async() =>
     {
         var namespaceBlob = await NamespaceHandler.FetchNamespaceBlobAsync(container, blob);
         if (!await namespaceBlob.ExistsAsync())
         {
             return new HandlerResult
             {
                 StatusCode = HttpStatusCode.NotFound,
             };
         }
         string accountName = namespaceBlob.SelectDataAccount(servePrimaryOnly);
         if (operationCanReplicateBlob)
         {
             if (namespaceBlob.IsReplicated ||
                 BlobReplicationHandler.ShouldReplicateBlob(requestWrapper.Headers, container, blob))
             {
                 accountName = namespaceBlob.PrimaryAccountName;
                 await BlobReplicationHandler.EnqueueBlobReplicationAsync(namespaceBlob, false);
             }
         }
         Uri redirect = ControllerOperations.GetRedirectUri(HttpContextFactory.Current.Request,
                                                            DashConfiguration.GetDataAccountByAccountName(accountName),
                                                            namespaceBlob.Container,
                                                            namespaceBlob.BlobName,
                                                            false);
         return HandlerResult.Redirect(requestWrapper, redirect);
     }));
 }
    protected override bool TryCreateViewer(FileInfo fileInfo, out HandlerResult?handlerResult)
    {
        var pcchOut = 0u;
        var riid    = typeof(IPreviewHandler).GUID.ToString("B");

        if (PInvoke.AssocQueryString(ASSOCF.ASSOCF_INIT_DEFAULTTOSTAR, ASSOCSTR.ASSOCSTR_SHELLEXTENSION, fileInfo.Extension, riid, Span <char> .Empty, ref pcchOut).Failed)
        {
            handlerResult = default;

            return(false);
        }

        var shellFileControl = new ShellFileControl();

        using (shellFileControl.Initialize())
        {
            shellFileControl.Loaded += (_, _) => shellFileControl.Open(fileInfo);
        }

        handlerResult = new HandlerResult {
            Viewer = shellFileControl
        };

        return(true);
    }
Example #16
0
        public void ProcessLongRunning(string replyTo, dynamic processor, dynamic args)
        {
            string agentTaskId = GenerateAgentTaskId();

            this.LongRunningAgentTask.Add(agentTaskId);

            string payload = @"{""value"":{""state"":""running"",""agent_task_id"":""" + agentTaskId + @"""}}";

            //Dictionary<string, object> payload = new Dictionary<string, object>()
            //{
            //        {   "value", new Dictionary<string, string>()
            //            {
            //                {"state", "running"} ,
            //                {"agent_task_id", "agent_task_id"}
            //            }
            //        }
            //};

            //YamlNode payloadYaml = YamlMapping.FromYaml(payload)[0];
            // todo: vladi: fix payload serialization
            this.Publish(replyTo, payload);

            //TODO : fix process
            string result = this.Process(processor, args).ToString();

            // todo: vladi: create a proper object
            HandlerResult resultsItem = new HandlerResult();

            resultsItem.Time        = DateTime.Now;
            resultsItem.AgentTaskId = agentTaskId;
            resultsItem.Result      = result;

            this.Results.Add(resultsItem);
            this.LongRunningAgentTask.Remove(agentTaskId);
        }
Example #17
0
    protected override bool TryCreateViewer(FileInfo fileInfo, out HandlerResult?handlerResult)
    {
        var highlighting = HighlightingManager.Instance.GetDefinitionByExtension(fileInfo.Extension);

        if (highlighting is null)
        {
            handlerResult = default;

            return(false);
        }

        var textEditor = new TextEditor();

        using (textEditor.Initialize())
        {
            textEditor.FontFamily         = new FontFamily("Consolas");
            textEditor.FontSize           = 14;
            textEditor.IsReadOnly         = true;
            textEditor.ShowLineNumbers    = true;
            textEditor.SyntaxHighlighting = highlighting;

            textEditor.Load(fileInfo.OpenReadNoLock());
        }

        handlerResult = new HandlerResult {
            Viewer = textEditor
        };

        return(true);
    }
Example #18
0
        public void RedirectionSignatureTest()
        {
            var request = new MockHttpRequestWrapper("GET", "http://localhost/container/test%20encoded", null)
            {
                AuthenticationScheme = "SharedKey",
                AuthenticationKey    = DashConfiguration.AccountKey,
            };
            var result = HandlerResult.Redirect(request,
                                                "http://dataaccount.blob.core.windows.net/container/test%20encoded");

            result.Headers = new ResponseHeaders(new[] {
                new KeyValuePair <string, string>("x-ms-date", "Wed, 01 Apr 2015 01:26:43 GMT"),
            });
            Assert.AreEqual(result.SignedLocation, "SharedKey dashstorage1:iU0kJCrvLR7rdIS/HXO0T04gTu09enDo25/3WtrjESI=");
            // Secondary key
            request = new MockHttpRequestWrapper("GET", "http://localhost/container/test%20encoded", null)
            {
                AuthenticationScheme = "SharedKeyLite",
                AuthenticationKey    = DashConfiguration.SecondaryAccountKey,
            };
            result = HandlerResult.Redirect(request,
                                            "http://dataaccount.blob.core.windows.net/container/test%20encoded");
            result.Headers = new ResponseHeaders(new[] {
                new KeyValuePair <string, string>("x-ms-date", "Wed, 01 Apr 2015 01:26:43 GMT"),
            });
            Assert.AreEqual(result.SignedLocation, "SharedKeyLite dashstorage1:o3XAz28naFjcSxCbqoZL394S/zLY2+nYk7v8KbdnlSI=");
        }
Example #19
0
        /// <summary>
        /// 数据处理
        /// </summary>
        HandlerResult IHandler.HandlerData(string openId, DataTypes intputType, object rawData)
        {
            //参数检查
            if (rawData == null)
            {
                throw new ArgumentNullException("rawData");
            }

            string text = rawData.ToString();

            if (MenuItems.ContainsKey(text))
            {
                TextMenuItem  meunItem = MenuItems[text];
                HandlerResult ret      = ((IHandler)meunItem.TextFullMatch).HandlerData(openId, intputType, text);

                if (ret == HandlerResult.Success)
                {
                    this.SuccessResponseResult = meunItem.JumpResult;
                }

                return(ret);
            }
            else
            {
                return(HandlerResult.Fail);
            }
        }
        public async Task WhenProcessMessageIsCalledWithMessageATheMessageAHandlerIsCalled()
        {
            IEnumerable <Type> MessageHandlerTypes()
            {
                return(new []
                {
                    typeof(HandlerA),
                    typeof(HandlerB),
                    typeof(NotAHandler)
                });
            }

            var scopeFactory = A.Fake <IServiceScopeFactory>();
            var scope        = A.Fake <IServiceScope>();
            var sp           = A.Fake <IServiceProvider>();
            var handler      = A.Fake <HandlerA>();

            A.CallTo(() => handler.Handle(A <MessageA> ._)).Returns(Task.FromResult(HandlerResult.Success()));

            A.CallTo(() => sp.GetService(A <Type> .That.IsEqualTo(typeof(HandlerA)))).Returns(handler);

            A.CallTo(() => scopeFactory.CreateScope()).Returns(scope);
            A.CallTo(() => scope.ServiceProvider).Returns(sp);

            var client   = A.Fake <IReceiverClient>();
            var registry = new MessageHandlerRegistry(MessageHandlerTypes);
            var sut      = new MessageDispatcher(scopeFactory, client, registry, new LogCorrelationHandler(false));

            await sut.ProcessMessage(typeof(MessageA).FullName, "{aProp1: \"hello\"}", () => Task.CompletedTask, m => Task.CompletedTask);

            A.CallTo(() => handler.Handle(A <MessageA> .That.Matches(m => m.AProp1 == "hello")))
            .MustHaveHappenedOnceExactly();
        }
Example #21
0
 protected async Task <HttpResponseMessage> DoHandlerAsync(string handlerName, Func <Task <HttpResponseMessage> > handler)
 {
     return(await WebOperationRunner.DoActionAsync(handlerName, handler, (ex) =>
     {
         return ProcessResultResponse(HandlerResult.FromException(ex));
     }));
 }
Example #22
0
        private static async Task <HandlerResult> EnumerateHandlers(
            HttpContext context,
            Type exceptionType,
            Exception exception,
            ExceptionHandlingPolicyOptions policyOptions,
            ILogger logger)
        {
            bool          handlerExecuted = false;
            HandlerResult handleResult    = HandlerResult.ReThrow;

            IEnumerable <Type> handlers = policyOptions.GetHandlersInternal(exceptionType);

            foreach (Type handlerType in handlers)
            {
                try
                {
                    IExceptionHandler handler =
                        context.RequestServices.GetService(handlerType) as IExceptionHandler;

                    if (handler == null)
                    {
                        handlerExecuted = false;
                        logger.LogError(Events.HandlerNotCreated,
                                        "Handler type {handlerType} can't be created because it not registered in IServiceProvider. RequestId: {RequestId}",
                                        handlerType, context.TraceIdentifier);
                    }
                    else
                    {
                        handleResult = await handler.Handle(context, exception);

                        handlerExecuted = true;
                    }
                }
                catch (Exception e)
                {
                    logger.LogError(Events.HandlerError, e,
                                    "Unhandled exception executing handler of type {handlerType} on exception of type {exceptionType}. RequestId: {RequestId}",
                                    handlerType, exceptionType, context.TraceIdentifier);

                    return(HandlerResult.ReThrow);
                }

                if (handleResult != HandlerResult.NextHandler)
                {
                    break;
                }
            }

            if (!handlerExecuted)
            {
                logger.LogWarning(Events.HandlersNotFound,
                                  "Handlers collection for exception type {exceptionType} is empty. Exception will be re-thrown. RequestId: {RequestId}",
                                  exceptionType, context.TraceIdentifier);

                return(HandlerResult.ReThrow);
            }

            return(handleResult);
        }
 public ReturnCode HandleResultAndReturnExitCode(HandlerResult handlerResult, string requestName)
 {
     if (handlerResult.IsSuccessful)
     {
         return(HandleSuccess(handlerResult, requestName));
     }
     else
     {
         return(HandleFailure(handlerResult, requestName));
     }
 }
        private ReturnCode HandleSuccess(HandlerResult handlerResult, string requestName)
        {
            _logger.LogInformation($"{requestName} successfully executed");

            if (handlerResult.Result != null)
            {
                _logger.LogInformation("RESULT:");
                _logger.LogInformation(JsonConvert.SerializeObject(handlerResult.Result));
            }

            return(ReturnCode.Success);
        }
Example #25
0
 /// <summary>
 /// Maps <see cref="HandlerResult{TValue}"/> to <see cref="ActionResult{TValue}"/>
 /// with suitable HTTP error codes.
 /// </summary>
 protected ActionResult <TValue> FromValueHandlerResult <TValue>(HandlerResult <TValue> result)
 {
     return(result.Status switch
     {
         HandlerCallStatus.Ok => Ok(result.Value),
         HandlerCallStatus.Created => Created(string.Empty, result.Value),
         HandlerCallStatus.EntityNotFound => NotFound(result.Messages.Any() ? result.Messages : new string[] { "Entity not found." }),
         HandlerCallStatus.UnauthorizedAccess => Unauthorized(),
         HandlerCallStatus.InvalidOperation => BadRequest(result.Messages),
         HandlerCallStatus.InvalidEntity => BadRequest(result.Messages),
         _ => throw new NotImplementedException(),
     });
Example #26
0
        public JsonResult UploadFile()
        {
            System.Web.HttpFileCollectionBase files = HttpContext.Request.Files; files = Request.Files;
            if (files == null || files.Count == 0)
            {
                return(null);
            }
            string attachmentId = Guid.NewGuid().ToString();

            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFileBase file = files[i] as System.Web.HttpPostedFileBase;
                if (file.ContentLength == 0)
                {
                    continue;
                }
                if (this.IsPostForm)
                {
                    attachmentId = files.AllKeys[i];
                }

                int checkResult = this.CheckFile(file);
                if (checkResult != 0 && checkResult != 1)
                {
                    //检查失败
                    var result = new HandlerResult(this.FileID, string.Empty, checkResult);
                    return(Json(result));
                }
                if (!string.IsNullOrEmpty(this.BizObjectID))
                {
                    if (this.Engine.BizObjectManager.GetAttachmentHeader(this.SchemaCode, this.BizObjectID, attachmentId) != null)
                    {
                        continue;
                    }
                }
                UploadFile(file, attachmentId);
            }

            if (!this.IsPostForm)
            {
                string url = AppConfig.GetReadAttachmentUrl(
                    this.IsMobile,
                    this.SchemaCode,
                    "",
                    attachmentId);
                var result = new HandlerResult(this.FileID, attachmentId, url);
                return(Json(result));
            }

            return(null);
        }
Example #27
0
        public HandlerResult Handle(HostelManagerState state, ICommand command, IRepository <IDbProperties> repository)
        {
            switch (command)
            {
            case ConstructHostel construct:
            {
                var hostel = construct.Construction;
                if (!state.Constructed)
                {
                    if (repository.ConstructHostel(hostel))
                    {
                        return(new HandlerResult(new ConstructedHostel(hostel)));
                    }
                    return(new HandlerResult($"Hostel {hostel.Detail.Name} could not be constructed at this time!", string.Empty, string.Empty));
                }
                return(new HandlerResult($"Hostel {hostel.Detail.Name} alread exist. Did the government demonish your hostel?", string.Empty, string.Empty));
            }

            case CreateFloor createFloor:
            {
                var floor = createFloor.Floor;
                if (repository.CreateFloor(floor))
                {
                    return(new HandlerResult(new CreatedFloor(floor)));
                }
                return(new HandlerResult($"Floor {floor.Tag} could not be created at this time!", createFloor.Commander, createFloor.CommandId));
            }

            case CreateSepticTank createSeptic:
            {
                var tank = createSeptic.Spec;
                if (repository.CreateSepticTank(tank))
                {
                    return(new HandlerResult(new CreatedSepticTank(tank)));
                }
                return(new HandlerResult($"SepticTank {tank.Tag} could not be created at this time!", createSeptic.Commander, createSeptic.CommandId));
            }

            case CreateWaterReservoir createWater:
            {
                var water = createWater.Spec;
                if (repository.CreateReservoir(water))
                {
                    return(new HandlerResult(new CreatedWaterReservoir(water)));
                }
                return(new HandlerResult($"Water Reservoir {water.Tag} could not be created at this time!", createWater.Commander, createWater.CommandId));
            }

            default: return(HandlerResult.NotHandled(command, command.Commander, command.CommandId));
            }
        }
Example #28
0
    protected override bool TryCreateViewer(FileInfo fileInfo, out HandlerResult?handlerResult)
    {
        var fileControl = new GenericFileControl();

        using (fileControl.Initialize())
        {
            fileControl.Open(fileInfo);
        }

        handlerResult = new HandlerResult {
            Viewer = fileControl
        };

        return(true);
    }
Example #29
0
    protected override bool TryCreateViewer(DirectoryInfo directoryInfo, out HandlerResult?handlerResult)
    {
        var directoryControl = new GenericDirectoryControl();

        using (directoryControl.Initialize())
        {
            directoryControl.Open(directoryInfo);
        }

        handlerResult = new HandlerResult {
            Viewer = directoryControl
        };

        return(true);
    }
Example #30
0
        static void Main(string[] args)
        {
            string path    = @"..\..\yaml\example.yml";
            string outpath = @"..\..\yaml\example.out.yml";

            if (args.Length > 0)
            {
                Dictionary <string, string> parms = new Dictionary <string, string>();
                parms["app"]  = "someApp";
                parms["type"] = "someType";
                using (StreamReader sr = new StreamReader(path))
                {
                    plan = Plan.FromYaml(sr);
                }
                plan.Progress += plan_Progress;
                HandlerResult result = plan.Start(parms, dryRun: false);
                Console.WriteLine(result);
                using (StreamWriter file = new StreamWriter(outpath))
                {
                    plan.ToYaml(file);
                }
            }
            else
            {
                ActionItem ac2 = ActionItem.CreateDummy("ac2");
                ActionItem ac1 = ActionItem.CreateDummy("ac1");
                ActionItem ac0 = ActionItem.CreateDummy("ac0");
                ac0.Actions = new List <ActionItem>();
                ac0.Actions.Add(ac1);
                List <ActionItem> actions = new List <ActionItem>();
                actions.Add(ac0);
                actions.Add(ac2);

                plan = new Plan()
                {
                    Name        = "plan0",
                    Actions     = actions,
                    Description = "planDesc",
                    IsActive    = true
                };

                using (StreamWriter file = new StreamWriter(path))
                {
                    plan.ToYaml(file);
                }
            }
            Console.Read();
        }
Example #31
0
 public override string GetUserOperationLog(bool iserror, LogLevel level, HandlerResult result,WebContext context) {
     return new {logout = (result.Data as Identity).Name}.stringify();
 }