Beispiel #1
0
		/*
		 * A result with a response body. If body is a ErrorResponseBody then Success will be set to false.
		 */
		public DebugResult(ResponseBody body) {
			Success = true;
			Body = body;
			if (body is ErrorResponseBody) {
				Success = false;
			}
		}
Beispiel #2
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="context"></param>
 public void ProcessRequest(HttpContext context)
 {
     ResponseType = ResponseType.Json;
     ResponseFormater = new JsonResponseFormater();
     var body = new ResponseBody();
     OnRequest(context, body);
     ProcessResponse(context.Response, body);
 }
Beispiel #3
0
		void IWebSocketListener.OnMessage(ResponseBody payload)
        {
            var handler = Message;
            if (handler != null)
            {
				handler(sender, new MessageEventArgs(payload));
            }
        }
Beispiel #4
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="context"></param>
 public byte[] ProcessRequest(IHttpRequestContext context)
 {
     ResponseType = ResponseType.Json;
     ResponseFormater = new JsonResponseFormater();
     var body = new ResponseBody();
     OnRequest(context, body);
     return ProcessResponse(context, body);
 }
Beispiel #5
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="httpResponse"></param>
 /// <param name="body"></param>
 protected void ProcessResponse(HttpResponse httpResponse, ResponseBody body)
 {
     try
     {
         SetResponseHead(httpResponse);
         var buffer = ResponseFormater.Serialize(body);
         httpResponse.BinaryWrite(buffer);
     }
     catch (Exception error)
     {
         TraceLog.WriteError("Response handle error:{0}", error);
         httpResponse.StatusCode = 500;
         httpResponse.StatusDescription = "Response error.";
     }
 }
 protected override void OnRequest(HttpContext context, ResponseBody body)
 {
     var watch = Stopwatch.StartNew();
     try
     {
         string param;
         if (CheckSign(context.Request, out param))
         {
             HandlerData handlerData;
             if (TryUrlQueryParse(param, out handlerData))
             {
                 body.Handler = handlerData.Name;
                 body.Data = HandlerManager.Excute(handlerData);
             }
             else
             {
                 body.StateCode = StateCode.NoHandler;
                 body.StateDescription = StateDescription.NoHandler;
             }
         }
         else
         {
             body.StateCode = StateCode.SignError;
             body.StateDescription = StateDescription.SignError;//"Sign error.";
         }
     }
     catch (HandlerException handlerError)
     {
         body.StateCode = handlerError.StateCode;
         body.StateDescription = handlerError.Message;
         TraceLog.WriteError("Request handle error:{0}", handlerError);
     }
     catch (Exception error)
     {
         body.StateCode = StateCode.Error;
         body.StateDescription = StateDescription.Error;// "Process request fail.";
         TraceLog.WriteError("Request handle error:{0}", error);
     }
     var ms = watch.ElapsedMilliseconds;
     if (ms > 20)
     {
         TraceLog.Write("Request timeout:{0}ms", ms);
     }
 }
Beispiel #7
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="context"></param>
 public void ProcessRequest(HttpContext context)
 {
     ResponseType = ResponseType.Json;
     ResponseFormater = new JsonResponseFormater();
     var body = new ResponseBody();
     try
     {
         string param;
         if (CheckSign(context.Request, out param))
         {
             HandlerData handlerData;
             if (TryUrlQueryParse(param, out handlerData))
             {
                 body.Handler = handlerData.Name;
                 body.Data = HandlerManager.Excute(handlerData);
             }
             else
             {
                 body.StateCode = StateCode.NoHandler;
                 body.StateDescription = string.Format("Not found \"{0}\" handler.", param);
             }
         }
         else
         {
             body.StateCode = StateCode.SignError;
             body.StateDescription = "Sign error.";
         }
     }
     catch (HandlerException handlerError)
     {
         body.StateCode = handlerError.StateCode;
         body.StateDescription = handlerError.Message;
         TraceLog.WriteError("Request handle error:{0}", handlerError);
     }
     catch (Exception error)
     {
         body.StateCode = StateCode.Error;
         body.StateDescription = "Process request fail.";
         TraceLog.WriteError("Request handle error:{0}", error);
     }
     ProcessResponse(context.Response, body);
 }
        public void Publish_SetsErrorStatusWhenResponseIsNull()
        {
            var gc = new Mock<IGregClient>();
            var rb = new ResponseBody();
            rb.success = false;
           
            gc.Setup(x => x.ExecuteAndDeserialize(It.IsAny<PackageUpload>())).Returns(rb);

            var pc = new PackageManagerClient(gc.Object, MockMaker.Empty<IPackageUploadBuilder>(), "");

            var pkg = new Package("", "Package", "0.1.0", "MIT");

            var handle = new PackageUploadHandle(PackageUploadBuilder.NewRequestBody(pkg));
            pc.Publish(pkg, Enumerable.Empty<string>(), true, handle);

            Assert.AreEqual(PackageUploadHandle.State.Error, handle.UploadState);
        }
Beispiel #9
0
 public void SetBody(ResponseBody bdy)
 {
     success = true;
     body    = bdy;
 }
Beispiel #10
0
		void IWebSocketListener.OnMessage(ResponseBody payload)
        {
            var handler = Message;
            if (handler != null)
            {
				handler(payload);
            }
        }
        /// <summary>
        /// Read Message from Memory
        /// </summary>
        /// <param name="Memory">Memory to read from</param>
        /// <param name="Location">Location of message</param>
        /// <returns>SMS Message</returns>
        public SMSMessage ReadMessage(String Memory, int Location)
        {
            // Check if disposed
            //if (_Disposed) throw new ObjectDisposedException();

            String ResponseBody;
            int    HeaderStart;
            int    HeaderEnd;
            int    MessageStart;
            int    MessageEnd;

            String Status      = "";
            String Orginator   = "";
            String ArrivalTime = "";
            String Message     = "";

            // Select Memory location
            if (ExecuteCommand("AT+CPMS=" + Memory, 15000) != GM862GPS.ResponseCodes.OK)
            {
                throw new Exception("Failed to set SMS Storage");
            }

            // Read Message from Location
            GM862GPS.ResponseCodes p = ExecuteCommand("AT+CMGR=" + Location.ToString(), 1000, out ResponseBody);

            /*if (ExecuteCommand("AT+CMGR=" + Location.ToString(), 1000, out ResponseBody) != GM862GPS.ResponseCodes.OK)
             *  throw new Exception("Failed to read SMS Storage");
             * */
            if (p != ResponseCodes.ERROR)
            {
                // Make sure there is no unsolicitated text in our message
                if (ResponseBody.IndexOf("\r\n\r\n") != -1)
                {
                    ResponseBody = ResponseBody.Substring(0, ResponseBody.IndexOf("\r\n\r\n") + 2);
                }

                // Check response
                HeaderStart = ResponseBody.IndexOf("+CMGR: ");
                if (HeaderStart == -1)
                {
                    throw new GM862GPSException("Malformed +CMGR response");
                }
                HeaderStart += "+CMGR: ".Length;
                HeaderEnd    = ResponseBody.IndexOf("\r\n", HeaderStart);
                if (HeaderEnd == -1)
                {
                    throw new GM862GPSException("Malformed +CMGR response");
                }

                // Skip <cr><lf>
                MessageStart = HeaderEnd + 2;
                MessageEnd   = ResponseBody.Length;
                if (MessageEnd == -1)
                {
                    throw new GM862GPSException("Malformed +CMGR response");
                }

                Message = ResponseBody.Substring(MessageStart, (MessageEnd - MessageStart) - 2);

                // Break up header
                System.Collections.ArrayList Header = new System.Collections.ArrayList();
                String HeaderPart  = "";
                bool   WithinQuote = false;
                foreach (char c in ResponseBody.Substring(HeaderStart, HeaderEnd + 2 - HeaderStart))
                {
                    if (c == '"')
                    {
                        WithinQuote = !WithinQuote; continue;
                    }
                    if (WithinQuote)
                    {
                        HeaderPart += c; continue;
                    }
                    if (c == ' ')
                    {
                        continue;
                    }
                    if (c == ',')
                    {
                        Header.Add(HeaderPart); HeaderPart = ""; continue;
                    }
                    if ((c == '\r') | (c == '\n'))
                    {
                        Header.Add(HeaderPart); HeaderPart = ""; break;
                    }
                }

                // Return message
                Status      = (String)Header[0];
                Orginator   = (String)Header[1];
                ArrivalTime = (String)Header[3];


                //*************** Delete SMS *******************
                ExecuteCommand("AT+CMGD=" + Location.ToString(), 15000, out ResponseBody);

                return(new SMSMessage(Memory, Location, Status, Orginator, ArrivalTime, Message));
            }
            else
            {
                return(new SMSMessage("", 0, "", "", "", ""));
            }
        }
Beispiel #12
0
        public override void OnLoad(HttpContext context)
        {
            base.OnLoad(context);
            requestBody             = new RequestBody();
            requestBody.accessToken = context.Request["accessToken"];
            requestBody.withId      = Convert.ToInt32(context.Request["withId"]);
            requestBody.page        = Convert.ToInt32(context.Request["page"]);
            requestBody.pageSize    = Convert.ToInt32(context.Request["pageSize"]);

            if (requestBody.accessToken == null || requestBody.accessToken.Trim().Length == 0 || requestBody.withId == 0)
            {
                SystemResponse.Output(SystemResponse.TYPE_NULLPARAMETER, out statusCode, out responseJson);
            }
            else
            {
                //验证用户
                TokenHelper    token          = new TokenHelper();
                UserTokenModel userTokenModel = token.getUserToken(requestBody.accessToken);
                if (userTokenModel == null)
                {
                    SystemResponse.Output(SystemResponse.TYPE_EXPIRE, out statusCode, out responseJson);
                }
                else
                {
                    //获取消息列表
                    ModelAdo <MsgModel> modelAdo = new ModelAdo <MsgModel>();
                    int pagenumber = requestBody.page == 0 ? 1 : requestBody.page;
                    int totalCount = 1;
                    modelAdo.PageSize = requestBody.pageSize == 0 ? modelAdo.PageSize : requestBody.pageSize;

                    List <MsgModel> models = models = modelAdo.GetList(pagenumber,
                                                                       "(ufrom=?ufrom AND uto=?uto) or (uto=?ufrom AND ufrom=?uto)", "createTime DESC ", out totalCount, "",
                                                                       new MySqlParameter("?ufrom", userTokenModel.uid),
                                                                       new MySqlParameter("?uto", requestBody.withId)
                                                                       );
                    if (models.Count >= 1)
                    {
                        //构建返回对象
                        List <Msg> msgs = new List <Msg>();
                        models.Sort(new idComparer());
                        foreach (MsgModel model in models)
                        {
                            Msg msg = new Msg();
                            msg.id         = model.id;
                            msg.content    = model.content;
                            msg.createTime = string.Format("{0:yyyy/MM/dd HH:mm:ss}", StringHelper.GetNomalTime(model.createTime));
                            msg.ufrom      = model.ufrom;
                            msg.uto        = model.uto;
                            msg.type       = model.type;
                            msg.status     = model.status;
                            msgs.Add(msg);
                            //处理数据为已读
                            if (msg.status == 0)
                            {
                                model.status = 1;
                                modelAdo.Update(model);
                            }
                        }
                        responseBody = new ResponseBody
                        {
                            page      = 1,
                            pageTotal = (totalCount + modelAdo.PageSize - 1) / modelAdo.PageSize,
                            total     = totalCount,
                            msgs      = msgs
                        };
                        responseJson = JsonConvert.SerializeObject(responseBody, Formatting.Indented);
                    }
                    else
                    {
                        SystemResponse.Output(SystemResponse.TYPE_NULL, out statusCode, out responseJson);
                    }
                }
            }
        }
Beispiel #13
0
        public override void Invoke(AMFContext context)
        {
            MessageOutput messageOutput = context.MessageOutput;

            for (int i = 0; i < context.AMFMessage.BodyCount; i++)
            {
                AMFBody      amfBody      = context.AMFMessage.GetBodyAt(i);
                ResponseBody responseBody = null;
                //Check for Flex2 messages and skip
                if (amfBody.IsEmptyTarget)
                {
                    continue;
                }

                //Check if response exists.
                responseBody = messageOutput.GetResponse(amfBody);
                if (responseBody != null)
                {
                    continue;
                }

                try
                {
                    MessageBroker   messageBroker   = _endpoint.GetMessageBroker();
                    RemotingService remotingService = messageBroker.GetService(RemotingService.RemotingServiceId) as RemotingService;
                    if (remotingService == null)
                    {
                        string serviceNotFound = __Res.GetString(__Res.Service_NotFound, RemotingService.RemotingServiceId);
                        responseBody = new ErrorResponseBody(amfBody, new AMFException(serviceNotFound));
                        messageOutput.AddBody(responseBody);
                        continue;
                    }
                    Destination destination = null;
                    if (destination == null)
                    {
                        destination = remotingService.GetDestinationWithSource(amfBody.TypeName);
                    }
                    if (destination == null)
                    {
                        destination = remotingService.DefaultDestination;
                    }
                    //At this moment we got a destination with the exact source or we have a default destination with the "*" source.
                    if (destination == null)
                    {
                        string destinationNotFound = __Res.GetString(__Res.Destination_NotFound, amfBody.TypeName);
                        responseBody = new ErrorResponseBody(amfBody, new AMFException(destinationNotFound));
                        messageOutput.AddBody(responseBody);
                        continue;
                    }

                    //Cache check
                    string source        = amfBody.TypeName + "." + amfBody.Method;
                    IList  parameterList = amfBody.GetParameterList();

                    FactoryInstance factoryInstance = destination.GetFactoryInstance();
                    factoryInstance.Source = amfBody.TypeName;
                    object instance = factoryInstance.Lookup();

                    if (instance != null)
                    {
                        bool isAccessible = TypeHelper.GetTypeIsAccessible(instance.GetType());
                        if (!isAccessible)
                        {
                            string msg = __Res.GetString(__Res.Type_InitError, amfBody.TypeName);
                            responseBody = new ErrorResponseBody(amfBody, new AMFException(msg));
                            messageOutput.AddBody(responseBody);
                            continue;
                        }

                        MethodInfo mi = null;
                        if (!amfBody.IsRecordsetDelivery)
                        {
                            mi = MethodHandler.GetMethod(instance.GetType(), amfBody.Method, amfBody.GetParameterList());
                        }
                        else
                        {
                            //will receive recordsetid only (ignore)
                            mi = instance.GetType().GetMethod(amfBody.Method);
                        }
                        if (mi != null)
                        {
                            #region Invocation handling
                            ParameterInfo[] parameterInfos = mi.GetParameters();
                            //Try to handle missing/optional parameters.
                            object[] args = new object[parameterInfos.Length];
                            if (!amfBody.IsRecordsetDelivery)
                            {
                                if (args.Length != parameterList.Count)
                                {
                                    string msg = __Res.GetString(__Res.Arg_Mismatch, parameterList.Count, mi.Name, args.Length);
                                    responseBody = new ErrorResponseBody(amfBody, new ArgumentException(msg));
                                    messageOutput.AddBody(responseBody);
                                    continue;
                                }
                                parameterList.CopyTo(args, 0);
                            }
                            else
                            {
                                if (amfBody.Target.EndsWith(".release"))
                                {
                                    responseBody = new ResponseBody(amfBody, null);
                                    messageOutput.AddBody(responseBody);
                                    continue;
                                }
                                string recordsetId = parameterList[0] as string;
                                string recordetDeliveryParameters = amfBody.GetRecordsetArgs();
                                byte[] buffer = System.Convert.FromBase64String(recordetDeliveryParameters);
                                recordetDeliveryParameters = System.Text.Encoding.UTF8.GetString(buffer);
                                if (recordetDeliveryParameters != null && recordetDeliveryParameters != string.Empty)
                                {
                                    string[] stringParameters = recordetDeliveryParameters.Split(new char[] { ',' });
                                    for (int j = 0; j < stringParameters.Length; j++)
                                    {
                                        if (stringParameters[j] == string.Empty)
                                        {
                                            args[j] = null;
                                        }
                                        else
                                        {
                                            args[j] = stringParameters[j];
                                        }
                                    }
                                    //TypeHelper.NarrowValues(argsStore, parameterInfos);
                                }
                            }

                            TypeHelper.NarrowValues(args, parameterInfos);

                            try
                            {
                                InvocationHandler invocationHandler = new InvocationHandler(mi);
                                object            result            = invocationHandler.Invoke(instance, args);

                                responseBody = new ResponseBody(amfBody, result);
                            }
                            catch (UnauthorizedAccessException exception)
                            {
                                responseBody = new ErrorResponseBody(amfBody, exception);
                            }
                            catch (Exception exception)
                            {
                                if (exception is TargetInvocationException && exception.InnerException != null)
                                {
                                    responseBody = new ErrorResponseBody(amfBody, exception.InnerException);
                                }
                                else
                                {
                                    responseBody = new ErrorResponseBody(amfBody, exception);
                                }
                            }
                            #endregion Invocation handling
                        }
                        else
                        {
                            responseBody = new ErrorResponseBody(amfBody, new MissingMethodException(amfBody.TypeName, amfBody.Method));
                        }
                    }
                    else
                    {
                        responseBody = new ErrorResponseBody(amfBody, new TypeInitializationException(amfBody.TypeName, null));
                    }
                }
                catch (Exception exception)
                {
                    responseBody = new ErrorResponseBody(amfBody, exception);
                }
                messageOutput.AddBody(responseBody);
            }
        }
Beispiel #14
0
 public string Build(ResponseBody responseBody)
 {
     return(JsonConvert.SerializeObject(responseBody, serializerSettings));
 }
Beispiel #15
0
        public IActionResult GetCascadeMenus()
        {
            var result = _menuService.GetCascadeMenus();

            return(Ok(ResponseBody.From(result)));
        }
Beispiel #16
0
 public IActionResult AddMenu([FromBody] AddOrUpdateMenuInput input)
 {
     _menuService.AddOrUpdateMenu(null, input);
     return(Ok(ResponseBody.From("保存成功")));
 }
Beispiel #17
0
        public IActionResult GetAllMenus([FromQuery] GetMenuInput input)
        {
            var result = _menuService.GetAllMenus(input);

            return(Ok(ResponseBody.From(result)));
        }
Beispiel #18
0
        public IActionResult GetMenusByRole()
        {
            var result = _menuService.GetMenusByRole();

            return(Ok(ResponseBody.From(result)));
        }
		public void SendResponse(Response response, ResponseBody body = null)
		{
			if (body != null)
			{
				response.SetBody(body);
			}
			SendMessage(response);
		}
Beispiel #20
0
 public Task EndAsync()
 {
     ResponseBody.Flush();
     return(TaskAsyncHelper.Empty);
 }
Beispiel #21
0
        public async Task Alexa_Function_Can_Process_Request()
        {
            // Arrange
            SkillRequest request = CreateRequest <LaunchRequest>();

            request.Request.Type = "LaunchRequest";

            string json = JsonConvert.SerializeObject(request);

            void Configure(IServiceCollection services)
            {
                services.AddLogging((builder) => builder.AddXUnit(this));
            }

            using var server = new LambdaTestServer(Configure);
            using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(2));

            await server.StartAsync(cancellationTokenSource.Token);

            LambdaTestContext context = await server.EnqueueAsync(json);

            // Queue a task to stop the Lambda function as soon as the response is processed
            _ = Task.Run(async() =>
            {
                await context.Response.WaitToReadAsync(cancellationTokenSource.Token);

                if (!cancellationTokenSource.IsCancellationRequested)
                {
                    cancellationTokenSource.Cancel();
                }
            });

            using var httpClient = server.CreateClient();

            // Act
            await FunctionEntrypoint.RunAsync(httpClient, cancellationTokenSource.Token);

            // Assert
            context.Response.TryRead(out LambdaTestResponse result).ShouldBeTrue();

            result.ShouldNotBeNull();
            result.IsSuccessful.ShouldBeTrue();
            result.Duration.ShouldBeInRange(TimeSpan.FromTicks(1), TimeSpan.FromSeconds(1));
            result.Content.ShouldNotBeEmpty();

            json = await result.ReadAsStringAsync();

            var actual = JsonConvert.DeserializeObject <SkillResponse>(json);

            actual.ShouldNotBeNull();

            ResponseBody response = AssertResponse(actual, shouldEndSession: false);

            response.Card.ShouldBeNull();
            response.Reprompt.ShouldBeNull();

            response.OutputSpeech.ShouldNotBeNull();
            response.OutputSpeech.Type.ShouldBe("SSML");

            var ssml = response.OutputSpeech.ShouldBeOfType <SsmlOutputSpeech>();

            ssml.Ssml.ShouldBe("<speak>Welcome to London Travel. You can ask me about disruption or for the status of any tube line, London Overground, the D.L.R. or T.F.L. Rail.</speak>");
        }
Beispiel #22
0
 public IActionResult AddMailSetting([FromBody] AddMailSettingInput input)
 {
     _mailSettingService.AddMailSetting(input);
     return(Ok(ResponseBody.From("保存成功")));
 }
Beispiel #23
0
 public IActionResult UpdateRole(int id, [FromBody] AddOrUpdateMenuInput input)
 {
     _menuService.AddOrUpdateMenu(id, input);
     return(Ok(ResponseBody.From("修改成功")));
 }
Beispiel #24
0
        public override void OnLoad(HttpContext context)
        {
            base.OnLoad(context);
            requestBody             = new RequestBody();
            requestBody.accessToken = context.Request["accessToken"];
            requestBody.page        = Convert.ToInt32(context.Request["page"]);
            requestBody.pageSize    = Convert.ToInt32(context.Request["pageSize"]);
            requestBody.status      = Convert.ToInt32(context.Request["status"]);
            if (requestBody.accessToken == null || requestBody.accessToken.Trim().Length == 0)
            {
                SystemResponse.Output(SystemResponse.TYPE_NULLPARAMETER, out statusCode, out responseJson);
            }
            //验证用户
            TokenHelper    token          = new TokenHelper();
            UserTokenModel userTokenModel = token.getUserToken(requestBody.accessToken);

            if (userTokenModel == null)
            {
                SystemResponse.Output(SystemResponse.TYPE_EXPIRE, out statusCode, out responseJson);
            }
            else
            {
                ModelAdo <SupplierOrderModel> orderModel = new ModelAdo <SupplierOrderModel>();
                List <SupplierOrderModel>     models     = null;
                int pagenumber = requestBody.page == 0 ? 1 : requestBody.page;
                int totalCount = 1;
                orderModel.PageSize = requestBody.pageSize == 0 ? orderModel.PageSize : requestBody.pageSize;

                if (requestBody.status == 4)
                {
                    ModelAdo <OrderModel> closeOrderModel  = new ModelAdo <OrderModel>();
                    List <OrderModel>     closeOrderModels = closeOrderModel.GetList(pagenumber, " sendUid=?sendUid AND ostatus=5", "", out totalCount, "",
                                                                                     new MySqlParameter("?sendUid", userTokenModel.uid)
                                                                                     );
                    if (closeOrderModels.Count >= 1)
                    {
                        //构建返回对象
                        List <Order> orders = new List <Order>();
                        foreach (OrderModel model in closeOrderModels)
                        {
                            Order order = new Order();
                            order.uid        = model.uid.ToString();
                            order.title      = model.title;
                            order.createDate = string.Format("{0:d}", StringHelper.GetNomalTime(model.createDate));
                            order.status     = model.ostatus;
                            order.price      = model.amount.ToString("f2");
                            order.oid        = model.id.ToString();
                            order.type       = model.otid;
                            Ext from = new Ext();
                            from.uid   = model.uid.ToString();
                            from.city  = model.address1;
                            from.date  = string.Format("{0:d}", StringHelper.GetNomalTime(model.time1));
                            order.from = from;

                            Ext to = new Ext();
                            to.uid   = model.uid.ToString();
                            to.city  = model.address2;
                            to.date  = string.Format("{0:d}", StringHelper.GetNomalTime(model.time2));
                            order.to = to;

                            orders.Add(order);
                        }
                        responseBody = new ResponseBody
                        {
                            page      = 1,
                            pageTotal = (totalCount + orderModel.PageSize - 1) / orderModel.PageSize,
                            total     = totalCount,
                            orders    = orders
                        };
                        responseJson = JsonConvert.SerializeObject(responseBody, Formatting.Indented);
                    }
                    else
                    {
                        SystemResponse.Output(SystemResponse.TYPE_NULL, out statusCode, out responseJson);
                    }
                }
                else
                {
                    if (requestBody.status == 0)
                    {
                        models = orderModel.GetList(pagenumber, " uid=?uid ", "", out totalCount, "",
                                                    new MySqlParameter("?uid", userTokenModel.uid)
                                                    );
                    }
                    else
                    {
                        models = orderModel.GetList(pagenumber, " uid=?uid AND status=?status", "", out totalCount, "",
                                                    new MySqlParameter("?uid", Convert.ToInt32(userTokenModel.uid)),
                                                    new MySqlParameter("?status", requestBody.status)
                                                    );
                    }

                    if (models.Count >= 1)
                    {
                        //构建返回对象
                        List <Order> orders = new List <Order>();
                        foreach (SupplierOrderModel model in models)
                        {
                            Order order = new Order();
                            order.uid        = model.uid.ToString();
                            order.oid        = model.oid.ToString();
                            order.title      = model.title;
                            order.createDate = string.Format("{0:d}", StringHelper.GetNomalTime(model.createDate));
                            order.status     = model.ostatus;
                            order.price      = model.amount.ToString("f2");
                            order.type       = model.otid;
                            Ext from = new Ext();
                            from.uid   = model.uid.ToString();
                            from.city  = model.address1;
                            from.date  = string.Format("{0:d}", StringHelper.GetNomalTime(model.time1));
                            order.from = from;

                            Ext to = new Ext();
                            to.uid   = model.uid.ToString();
                            to.city  = model.address2;
                            to.date  = string.Format("{0:d}", StringHelper.GetNomalTime(model.time2));
                            order.to = to;

                            orders.Add(order);
                        }
                        responseBody = new ResponseBody
                        {
                            page      = 1,
                            pageTotal = (totalCount + orderModel.PageSize - 1) / orderModel.PageSize,
                            total     = totalCount,
                            orders    = orders
                        };
                        responseJson = JsonConvert.SerializeObject(responseBody, Formatting.Indented);
                    }
                    else
                    {
                        SystemResponse.Output(SystemResponse.TYPE_NULL, out statusCode, out responseJson);
                    }
                }
            }
        }
Beispiel #25
0
 public IActionResult DeleteMenu(int[] ids)
 {
     _menuService.DeleteMenu(ids);
     return(Ok(ResponseBody.From("删除成功")));
 }
Beispiel #26
0
        public object SignOut(User request)
        {
            var response = new ResponseBody();

            return(response);
        }
        public SkillResponse Prescreen(SkillRequest alexaRequestInput)
        {
            AlexaRequestValidationService    validator        = new AlexaRequestValidationService();
            SpeechletRequestValidationResult validationResult = validator.ValidateAlexaRequest(alexaRequestInput);

            if (validationResult != SpeechletRequestValidationResult.OK)
            {
                logger.Debug("validation error: " + validationResult.ToString());
                new Exception("Invalid Request");
            }
            SkillResponse response = new SkillResponse();

            response.Version = "1.0";
            logger.Debug("Request:" + JsonConvert.SerializeObject(alexaRequestInput.Request));

            switch (alexaRequestInput.Request.Type)
            {
            case "LaunchRequest":

                //   logger.Debug("Launch request in");

                response.Response      = new ResponseBody();
                response.Response.Card = new SimpleCard()
                {
                    Content = "Hello!! Welcome to the Kentucky Health eligibility finder! Lets answer a few questions together to see the benefits you could have through the Kentucky HEALTH program. Say \"I am ready\" when ready to start.",

                    Title = "Welcome!!"
                };
                response.Response.OutputSpeech = new PlainTextOutputSpeech()
                {
                    Text = "Hello!! Welcome to Kentucky Health eligibility finder! Lets answer a few questions together and see what types of requirements and benefits you may have through the Kentucky HEALTH program. When ready, say, \"I am ready!\""
                };
                //response.Response.OutputSpeech = new PlainTextOutputSpeech() { Text = "Hello!! say, \"I am ready!\"" };
                response.Response.Reprompt         = new Reprompt("Please say, I am ready.");
                response.Response.ShouldEndSession = false;

                //  logger.Debug("Launch request out");
                break;

            case "SessionEndedRequest":
                response.Response      = new ResponseBody();
                response.Response.Card = new SimpleCard()
                {
                    Content = "Goodbye, have a good day!",

                    Title = "Welcome!!"
                };
                response.Response.OutputSpeech = new PlainTextOutputSpeech()
                {
                    Text = "Goodbye, have a good day!"
                };
                response.Response.ShouldEndSession = true;
                return(response);

            case "IntentRequest":
                try
                {
                    CaseInfo      caseInfo      = Helpers.GetCaseInfo(alexaRequestInput.Session.SessionId);
                    IntentRequest intentRequest = (IntentRequest)alexaRequestInput.Request;
                    //if (intentRequest.Intent.Name == "repeat")
                    //{
                    //    response.Response = GetResponseForSlot(caseInfo.LastAskedSlot, caseInfo.ChildName, caseInfo.EligibilityGroup);
                    //    response.Version = "1.0";
                    //    response.Response.ShouldEndSession = false;
                    //}

                    if (intentRequest.Intent.Name == "PreScreen")
                    {
                        UpdateModel(caseInfo, intentRequest.Intent);
                        string slot = GetNextSlot(caseInfo);

                        ResponseBody body = GetResponseForSlot(slot, caseInfo.ChildName, caseInfo.EligibilityGroup);
                        if (slot.Contains("EG_"))
                        {
                            caseInfo.EligibilityGroup = slot;
                            slot = "conclude";
                        }
                        caseInfo.LastAskedSlot = slot;
                        response.Response      = body;
                        if (body.ShouldEndSession == true)
                        {
                            Helpers.RemoveCaseInfo(alexaRequestInput.Session.SessionId);
                        }
                    }

                    if (intentRequest.Intent.Name == "AMAZON.StopIntent")
                    {
                        var stophandler   = new AMAZON_StopIntent();
                        var skillresponse = stophandler.HandleIntent(null, null, null, null, logger);
                        skillresponse.Version = "1.0";
                        return(skillresponse);
                    }
                    if (intentRequest.Intent.Name == "AMAZON.FallbackIntent")
                    {
                        var fallbackhandler  = new AMAZON_FallbackIntent();
                        var fallbackresponse = fallbackhandler.HandleIntent(null, null, null, null, logger);
                        fallbackresponse.Version = "1.0";
                        return(fallbackresponse);
                    }
                    if (intentRequest.Intent.Name == "AMAZON.CancelIntent")
                    {
                        var cancelhandler   = new AMAZON_CancelIntent();
                        var cancellresponse = cancelhandler.HandleIntent(null, null, null, null, logger);
                        cancellresponse.Version = "1.0";
                        return(cancellresponse);
                    }
                    //if (intentRequest.Intent.Name == "AMAZON.HelpIntent")
                    //{
                    //    var helphandler = new AMAZON_HelpIntent();
                    //    var helplresponse = helphandler.HandleIntent(null, null, null, null, logger);
                    //    helplresponse.Version = "1.0";
                    //    helplresponse.Response.ShouldEndSession = false;
                    //    return helplresponse;
                    //}
                    break;
                }
                catch (Exception e)
                {
                    response.Response = Helpers.GetPlainTextResponseBody("Aaargh, the application encountered an error. Please try again later. Sorry for the inconvenience", true, "Error", e.Message);
                    response.Response.ShouldEndSession = true;
                    logger.Debug(e.StackTrace);
                }
                break;
            }
            logger.Debug("Response:" + JsonConvert.SerializeObject(response.Response));

            return(response);
        }
Beispiel #28
0
        public override void Invoke(AMFContext context)
        {
            MessageOutput messageOutput = context.MessageOutput;

            for (int i = 0; i < context.AMFMessage.BodyCount; i++)
            {
                AMFBody      amfBody      = context.AMFMessage.GetBodyAt(i);
                ResponseBody responseBody = null;
                //Check for Flex2 messages and skip
                if (amfBody.IsEmptyTarget)
                {
                    continue;
                }

                if (amfBody.IsDebug)
                {
                    continue;
                }
                if (amfBody.IsDescribeService)
                {
                    responseBody = new ResponseBody();
                    responseBody.IgnoreResults = amfBody.IgnoreResults;
                    responseBody.Target        = amfBody.Response + AMFBody.OnResult;
                    responseBody.Response      = null;
                    DescribeService describeService = new DescribeService(amfBody);
                    responseBody.Content = describeService.GetDescription();
                    messageOutput.AddBody(responseBody);
                    continue;
                }

                //Check if response exists.
                responseBody = messageOutput.GetResponse(amfBody);
                if (responseBody != null)
                {
                    continue;
                }

                try
                {
                    MessageBroker   messageBroker   = _endpoint.GetMessageBroker();
                    RemotingService remotingService = messageBroker.GetService(RemotingService.RemotingServiceId) as RemotingService;
                    if (remotingService == null)
                    {
                        string serviceNotFound = __Res.GetString(__Res.Service_NotFound, RemotingService.RemotingServiceId);
                        responseBody = new ErrorResponseBody(amfBody, new FluorineException(serviceNotFound));
                        messageOutput.AddBody(responseBody);
                        if (log.IsErrorEnabled)
                        {
                            log.Error(serviceNotFound);
                        }
                        continue;
                    }
                    Destination destination = null;
                    if (destination == null)
                    {
                        destination = remotingService.GetDestinationWithSource(amfBody.TypeName);
                    }
                    if (destination == null)
                    {
                        destination = remotingService.DefaultDestination;
                    }
                    //At this moment we got a destination with the exact source or we have a default destination with the "*" source.
                    if (destination == null)
                    {
                        string destinationNotFound = __Res.GetString(__Res.Destination_NotFound, amfBody.TypeName);
                        responseBody = new ErrorResponseBody(amfBody, new FluorineException(destinationNotFound));
                        messageOutput.AddBody(responseBody);
                        if (log.IsErrorEnabled)
                        {
                            log.Error(destinationNotFound);
                        }
                        continue;
                    }

                    try
                    {
                        remotingService.CheckSecurity(destination);
                    }
                    catch (UnauthorizedAccessException exception)
                    {
                        responseBody = new ErrorResponseBody(amfBody, exception);
                        if (log.IsDebugEnabled)
                        {
                            log.Debug(exception.Message);
                        }
                        continue;
                    }

                    //Cache check
                    string source        = amfBody.TypeName + "." + amfBody.Method;
                    IList  parameterList = amfBody.GetParameterList();
                    string key           = dotFlex.Configuration.CacheMap.GenerateCacheKey(source, parameterList);
                    if (FluorineConfiguration.Instance.CacheMap.ContainsValue(key))
                    {
                        object result = dotFlex.Configuration.FluorineConfiguration.Instance.CacheMap.Get(key);
                        if (result != null)
                        {
                            if (log != null && log.IsDebugEnabled)
                            {
                                log.Debug(__Res.GetString(__Res.Cache_HitKey, source, key));
                            }
                            responseBody = new ResponseBody(amfBody, result);
                            messageOutput.AddBody(responseBody);
                            continue;
                        }
                    }

                    FactoryInstance factoryInstance = destination.GetFactoryInstance();
                    factoryInstance.Source = amfBody.TypeName;
                    if (FluorineContext.Current.ActivationMode != null)                 //query string can override the activation mode
                    {
                        factoryInstance.Scope = FluorineContext.Current.ActivationMode;
                    }
                    object instance = factoryInstance.Lookup();

                    if (instance != null)
                    {
                        try
                        {
                            bool isAccessible = TypeHelper.GetTypeIsAccessible(instance.GetType());
                            if (!isAccessible)
                            {
                                string msg = __Res.GetString(__Res.Type_InitError, amfBody.TypeName);
                                if (log.IsErrorEnabled)
                                {
                                    log.Error(msg);
                                }
                                responseBody = new ErrorResponseBody(amfBody, new FluorineException(msg));
                                messageOutput.AddBody(responseBody);
                                continue;
                            }

                            MethodInfo mi = null;
                            if (!amfBody.IsRecordsetDelivery)
                            {
                                mi = MethodHandler.GetMethod(instance.GetType(), amfBody.Method, amfBody.GetParameterList());
                            }
                            else
                            {
                                //will receive recordsetid only (ignore)
                                mi = instance.GetType().GetMethod(amfBody.Method);
                            }
                            if (mi != null)
                            {
                                object[] roleAttributes = mi.GetCustomAttributes(typeof(RoleAttribute), true);
                                if (roleAttributes != null && roleAttributes.Length == 1)
                                {
                                    RoleAttribute roleAttribute = roleAttributes[0] as RoleAttribute;
                                    string[]      roles         = roleAttribute.Roles.Split(',');

                                    bool authorized = messageBroker.LoginManager.DoAuthorization(roles);
                                    if (!authorized)
                                    {
                                        throw new UnauthorizedAccessException(__Res.GetString(__Res.Security_AccessNotAllowed));
                                    }
                                }

                                #region Invocation handling
                                PageSizeAttribute pageSizeAttribute  = null;
                                MethodInfo        miCounter          = null;
                                object[]          pageSizeAttributes = mi.GetCustomAttributes(typeof(PageSizeAttribute), true);
                                if (pageSizeAttributes != null && pageSizeAttributes.Length == 1)
                                {
                                    pageSizeAttribute = pageSizeAttributes[0] as PageSizeAttribute;
                                    miCounter         = instance.GetType().GetMethod(amfBody.Method + "Count");
                                    if (miCounter != null && miCounter.ReturnType != typeof(System.Int32))
                                    {
                                        miCounter = null; //check signature
                                    }
                                }
                                ParameterInfo[] parameterInfos = mi.GetParameters();
                                //Try to handle missing/optional parameters.
                                object[] args = new object[parameterInfos.Length];
                                if (!amfBody.IsRecordsetDelivery)
                                {
                                    if (args.Length != parameterList.Count)
                                    {
                                        string msg = __Res.GetString(__Res.Arg_Mismatch, parameterList.Count, mi.Name, args.Length);
                                        if (log != null && log.IsErrorEnabled)
                                        {
                                            log.Error(msg);
                                        }
                                        responseBody = new ErrorResponseBody(amfBody, new ArgumentException(msg));
                                        messageOutput.AddBody(responseBody);
                                        continue;
                                    }
                                    parameterList.CopyTo(args, 0);
                                    if (pageSizeAttribute != null)
                                    {
                                        PagingContext pagingContext = new PagingContext(pageSizeAttribute.Offset, pageSizeAttribute.Limit);
                                        PagingContext.SetPagingContext(pagingContext);
                                    }
                                }
                                else
                                {
                                    if (amfBody.Target.EndsWith(".release"))
                                    {
                                        responseBody = new ResponseBody(amfBody, null);
                                        messageOutput.AddBody(responseBody);
                                        continue;
                                    }
                                    string recordsetId = parameterList[0] as string;
                                    string recordetDeliveryParameters = amfBody.GetRecordsetArgs();
                                    byte[] buffer = System.Convert.FromBase64String(recordetDeliveryParameters);
                                    recordetDeliveryParameters = System.Text.Encoding.UTF8.GetString(buffer);
                                    if (recordetDeliveryParameters != null && recordetDeliveryParameters != string.Empty)
                                    {
                                        string[] stringParameters = recordetDeliveryParameters.Split(new char[] { ',' });
                                        for (int j = 0; j < stringParameters.Length; j++)
                                        {
                                            if (stringParameters[j] == string.Empty)
                                            {
                                                args[j] = null;
                                            }
                                            else
                                            {
                                                args[j] = stringParameters[j];
                                            }
                                        }
                                        //TypeHelper.NarrowValues(argsStore, parameterInfos);
                                    }
                                    PagingContext pagingContext = new PagingContext(System.Convert.ToInt32(parameterList[1]), System.Convert.ToInt32(parameterList[2]));
                                    PagingContext.SetPagingContext(pagingContext);
                                }

                                TypeHelper.NarrowValues(args, parameterInfos);

                                try
                                {
                                    InvocationHandler invocationHandler = new InvocationHandler(mi);
                                    object            result            = invocationHandler.Invoke(instance, args);

                                    if (FluorineConfiguration.Instance.CacheMap != null && FluorineConfiguration.Instance.CacheMap.ContainsCacheDescriptor(source))
                                    {
                                        //The result should be cached
                                        CacheableObject cacheableObject = new CacheableObject(source, key, result);
                                        FluorineConfiguration.Instance.CacheMap.Add(cacheableObject.Source, cacheableObject.CacheKey, cacheableObject);
                                        result = cacheableObject;
                                    }
                                    responseBody = new ResponseBody(amfBody, result);

                                    if (pageSizeAttribute != null)
                                    {
                                        int    totalCount  = 0;
                                        string recordsetId = null;

                                        IList  list = amfBody.GetParameterList();
                                        string recordetDeliveryParameters = null;
                                        if (!amfBody.IsRecordsetDelivery)
                                        {
                                            //fist call paging
                                            object[] argsStore = new object[list.Count];
                                            list.CopyTo(argsStore, 0);
                                            recordsetId = System.Guid.NewGuid().ToString();
                                            if (miCounter != null)
                                            {
                                                //object[] counterArgs = new object[0];
                                                totalCount = (int)miCounter.Invoke(instance, args);
                                            }
                                            string[] stringParameters = new string[argsStore.Length];
                                            for (int j = 0; j < argsStore.Length; j++)
                                            {
                                                if (argsStore[j] != null)
                                                {
                                                    stringParameters[j] = argsStore[j].ToString();
                                                }
                                                else
                                                {
                                                    stringParameters[j] = string.Empty;
                                                }
                                            }
                                            recordetDeliveryParameters = string.Join(",", stringParameters);
                                            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(recordetDeliveryParameters);
                                            recordetDeliveryParameters = System.Convert.ToBase64String(buffer);
                                        }
                                        else
                                        {
                                            recordsetId = amfBody.GetParameterList()[0] as string;
                                        }
                                        if (result is DataTable)
                                        {
                                            DataTable dataTable = result as DataTable;
                                            dataTable.ExtendedProperties["TotalCount"]  = totalCount;
                                            dataTable.ExtendedProperties["Service"]     = recordetDeliveryParameters + "/" + amfBody.Target;
                                            dataTable.ExtendedProperties["RecordsetId"] = recordsetId;
                                            if (amfBody.IsRecordsetDelivery)
                                            {
                                                dataTable.ExtendedProperties["Cursor"]      = Convert.ToInt32(list[list.Count - 2]);
                                                dataTable.ExtendedProperties["DynamicPage"] = true;
                                            }
                                        }
                                    }
                                }
                                catch (UnauthorizedAccessException exception)
                                {
                                    responseBody = new ErrorResponseBody(amfBody, exception);
                                    if (log.IsDebugEnabled)
                                    {
                                        log.Debug(exception.Message);
                                    }
                                }
                                catch (Exception exception)
                                {
                                    if (exception is TargetInvocationException && exception.InnerException != null)
                                    {
                                        responseBody = new ErrorResponseBody(amfBody, exception.InnerException);
                                    }
                                    else
                                    {
                                        responseBody = new ErrorResponseBody(amfBody, exception);
                                    }
                                    if (log.IsDebugEnabled)
                                    {
                                        log.Debug(__Res.GetString(__Res.Invocation_Failed, mi.Name, exception.Message));
                                    }
                                }
                                #endregion Invocation handling
                            }
                            else
                            {
                                responseBody = new ErrorResponseBody(amfBody, new MissingMethodException(amfBody.TypeName, amfBody.Method));
                            }
                        }
                        finally
                        {
                            factoryInstance.OnOperationComplete(instance);
                        }
                    }
                    else
                    {
                        responseBody = new ErrorResponseBody(amfBody, new TypeInitializationException(amfBody.TypeName, null));
                    }
                }
                catch (Exception exception)
                {
                    if (log != null && log.IsErrorEnabled)
                    {
                        log.Error(exception.Message, exception);
                    }
                    responseBody = new ErrorResponseBody(amfBody, exception);
                }
                messageOutput.AddBody(responseBody);
            }
        }
        [AllowAnonymous] // No authorization required for Login Request, obviously
        public async Task <dynamic> Post([FromBody] LoginRequest requestBody)
        {
            this.EnsureModelValidation();

            var collection = MongoWrapper.Database.GetCollection <Models.User>(nameof(User));

            var projectionBuilder = new ProjectionDefinitionBuilder <Models.User>();
            var projection        = projectionBuilder
                                    .Include(u => u.Password)
                                    .Include(u => u.Avatar)
                                    .Include(u => u.FullName)
                                    .Include("_t");

            var filterBuilder = new FilterDefinitionBuilder <Models.User>();
            var filter        = filterBuilder.And(
                filterBuilder.Eq(u => u.Email, requestBody.Email),
                GeneralUtils.NotDeactivated(filterBuilder)
                );

            var user = (await collection.FindAsync(filter, new FindOptions <Models.User>
            {
                Limit = 1,
                Projection = projection,
            })).SingleOrDefault();

            var responseBody = new ResponseBody();

            if (user == null)
            {
                responseBody.Code    = ResponseCode.NotFound;
                responseBody.Success = false;
                responseBody.Message = "Usuário não encontrado!";
                Response.StatusCode  = (int)HttpStatusCode.Unauthorized;
                return(responseBody);
            }

            var passwordMatchesTask = Task.Run(() => Encryption.Compare(requestBody.Password, user.Password));

            var(creationDate, expiryDate, token) = await AuthenticationUtils.GenerateJwtTokenForUser(user._id.ToString(), TokenConfigurations, SigningConfigurations);

            bool passwordMatches = await passwordMatchesTask;

            if (!passwordMatches)
            {
                responseBody.Message = "Senha incorreta!";
                responseBody.Code    = ResponseCode.IncorrectPassword;
                responseBody.Success = false;
                Response.StatusCode  = (int)HttpStatusCode.Unauthorized;
                return(responseBody);
            }

            responseBody.Message = "Login efetuado com sucesso!";
            responseBody.Code    = ResponseCode.GenericSuccess;
            responseBody.Success = true;
            responseBody.Data    = new
            {
                user = new
                {
                    user.Kind,
                    user.Avatar,
                    user.FullName,
                },
                tokenData = new
                {
                    created     = creationDate,
                    expiration  = expiryDate,
                    accessToken = token,
                }
            };
            Response.StatusCode = (int)HttpStatusCode.OK;
            return(responseBody);
        }
Beispiel #30
0
        /*
         * TODO: More work on the response codes.  Right now
         * returning 200 for success or 499 for exception
         */

        public void SendRequest()
        {
            Culture.SetCurrentCulture();
            HttpWebResponse response = null;
            StringBuilder   sb       = new StringBuilder();

            byte[] buf        = new byte[8192];
            string tempString = null;
            int    count      = 0;

            try
            {
                Request = (HttpWebRequest)WebRequest.Create(Url);

                Request.Method      = HttpMethod;
                Request.ContentType = HttpMIMEType;

                if (!HttpVerifyCert)
                {
                    // Connection Group Name is probably not used so we hijack it to identify
                    // a desired security exception
//                  Request.ConnectionGroupName="NoVerify";
                    Request.Headers.Add("NoVerifyCert", "true");
                }
//              else
//              {
//                  Request.ConnectionGroupName="Verify";
//              }

                if (!string.IsNullOrEmpty(proxyurl))
                {
                    if (!string.IsNullOrEmpty(proxyexcepts))
                    {
                        string[] elist = proxyexcepts.Split(';');
                        Request.Proxy = new WebProxy(proxyurl, true, elist);
                    }
                    else
                    {
                        Request.Proxy = new WebProxy(proxyurl, true);
                    }
                }

                foreach (KeyValuePair <string, string> entry in ResponseHeaders)
                {
                    if (entry.Key.ToLower().Equals("user-agent"))
                    {
                        Request.UserAgent = entry.Value;
                    }
                    else
                    {
                        Request.Headers[entry.Key] = entry.Value;
                    }
                }

                // Encode outbound data
                if (OutboundBody.Length > 0)
                {
                    byte[] data = Util.UTF8.GetBytes(OutboundBody);

                    Request.ContentLength = data.Length;
                    Stream bstream = Request.GetRequestStream();
                    bstream.Write(data, 0, data.Length);
                    bstream.Close();
                }

                Request.Timeout = HttpTimeout;
                // execute the request
                try
                {
                    // execute the request
                    response = (HttpWebResponse)Request.GetResponse();
                }
                catch (WebException e)
                {
                    if (e.Status != WebExceptionStatus.ProtocolError)
                    {
                        throw;
                    }
                    response = (HttpWebResponse)e.Response;
                }

                Status = (int)response.StatusCode;

                Stream resStream = response.GetResponseStream();

                do
                {
                    // fill the buffer with data
                    count = resStream.Read(buf, 0, buf.Length);

                    // make sure we read some data
                    if (count != 0)
                    {
                        // translate from bytes to ASCII text
                        tempString = Util.UTF8.GetString(buf, 0, count);

                        // continue building the string
                        sb.Append(tempString);
                    }
                } while (count > 0); // any more data to read?

                ResponseBody = sb.ToString();

                if (ResponseBody.Length > MaxLength) //Cut it off then
                {
                    ResponseBody = ResponseBody.Remove(MaxLength);
                    //Add the metaData
                    Metadata = new object[2] {
                        0, MaxLength
                    };
                }
            }
            catch (Exception e)
            {
                //Too many for this prim, return status 499
                Status       = (int)499;
                ResponseBody = e.Message;

                _finished = true;
                return;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }

            Status    = (int)HttpStatusCode.OK;
            _finished = true;
        }
Beispiel #31
0
		public void SetBody(ResponseBody bdy) {
			success = true;
			body = bdy;
		}
        object ProcessMessage(AMFMessage amfMessage)
        {
            // Apply AMF-based operation selector

            /*
             * Dictionary<string, string> operationNameDictionary = new Dictionary<string, string>();
             * foreach (OperationDescription operation in _endpoint.Contract.Operations)
             * {
             *  try
             *  {
             *      operationNameDictionary.Add(operation.Name.ToLower(), operation.Name);
             *  }
             *  catch (ArgumentException)
             *  {
             *      throw new Exception(String.Format("The specified contract cannot be used with case insensitive URI dispatch because there is more than one operation named {0}", operation.Name));
             *  }
             * }
             */

            //SessionMode, CallbackContract, ProtectionLevel

            AMFMessage output = new AMFMessage(amfMessage.Version);

            for (int i = 0; i < amfMessage.BodyCount; i++)
            {
                AMFBody amfBody = amfMessage.GetBodyAt(i);
                object  content = amfBody.Content;
                if (content is IList)
                {
                    content = (content as IList)[0];
                }
                IMessage message = content as IMessage;
                if (message != null)
                {
                    //WCF should not assign client id for Flex...
                    if (message.clientId == null)
                    {
                        message.clientId = Guid.NewGuid().ToString("D");
                    }

                    //IMessage resultMessage = _endpoint.ServiceMessage(message);
                    IMessage       responseMessage = null;
                    CommandMessage commandMessage  = message as CommandMessage;
                    if (commandMessage != null && commandMessage.operation == CommandMessage.ClientPingOperation)
                    {
                        responseMessage      = new AcknowledgeMessage();
                        responseMessage.body = true;
                    }
                    else
                    {
                        RemotingMessage remotingMessage = message as RemotingMessage;
                        string          operation       = remotingMessage.operation;
                        //TODO: you could use an alias for a contract to expose a different name to the clients in the metadata using the Name property of the ServiceContract attribute
                        string source            = remotingMessage.source;
                        Type   serviceType       = TypeHelper.Locate(source);
                        Type   contractInterface = serviceType.GetInterface(_endpoint.Contract.ContractType.FullName);
                        //WCF also lets you apply the ServiceContract attribute directly on the service class. Avoid using it.
                        //ServiceContractAttribute serviceContractAttribute = ReflectionUtils.GetAttribute(typeof(ServiceContractAttribute), type, true) as ServiceContractAttribute;
                        if (contractInterface != null)
                        {
                            object     instance      = Activator.CreateInstance(serviceType);
                            IList      parameterList = remotingMessage.body as IList;
                            MethodInfo mi            = MethodHandler.GetMethod(contractInterface, operation, parameterList, false, false);
                            if (mi != null)
                            {
                                //TODO OperationContract attribute to alias it to a different publicly exposed name
                                OperationContractAttribute operationContractAttribute = ReflectionUtils.GetAttribute(typeof(OperationContractAttribute), mi, true) as OperationContractAttribute;
                                if (operationContractAttribute != null)
                                {
                                    ParameterInfo[] parameterInfos = mi.GetParameters();
                                    object[]        args           = new object[parameterInfos.Length];
                                    parameterList.CopyTo(args, 0);
                                    TypeHelper.NarrowValues(args, parameterInfos);
                                    try
                                    {
                                        object result = mi.Invoke(instance, args);
                                        if (!(result is IMessage))
                                        {
                                            responseMessage      = new AcknowledgeMessage();
                                            responseMessage.body = result;
                                        }
                                        else
                                        {
                                            responseMessage = result as IMessage;
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        // Lets FluorineFx return ErrorMessages in case the method invocation fails with an exception
                                        responseMessage = ErrorMessage.GetErrorMessage(remotingMessage, e.InnerException);
                                    }
                                }
                                else
                                {
                                    responseMessage = ErrorMessage.GetErrorMessage(remotingMessage, new SecurityException("Method in not part of a service contract"));
                                }
                            }
                            else
                            {
                                responseMessage = ErrorMessage.GetErrorMessage(remotingMessage, new SecurityException("Method in not part of a service contract"));
                            }
                        }
                        else
                        {
                            responseMessage = ErrorMessage.GetErrorMessage(remotingMessage, new SecurityException(String.Format("The specified contract {0} cannot be used with the source named {1} and operation named {2}", _endpoint.Contract.ContractType.Name, source, operation)));
                        }
                    }

                    if (responseMessage is AsyncMessage)
                    {
                        ((AsyncMessage)responseMessage).correlationId = message.messageId;
                    }
                    responseMessage.destination = message.destination;
                    responseMessage.clientId    = message.clientId;

                    ResponseBody responseBody = new ResponseBody(amfBody, responseMessage);
                    output.AddBody(responseBody);
                }
            }
            return(output);
        }
Beispiel #33
0
        public TodoResponse DeleteToDo(int id)
        {
            TodoResponse   todoResponse   = new TodoResponse();
            ResponseHeader responseHeader = new ResponseHeader();
            ResponseBody   responseBody   = new ResponseBody();
            string         statusMessage  = string.Empty;
            HttpStatusCode statusCode;
            List <Error>   errorlist = new List <Error>();

            try
            {
                ToDo toDo = _repository.getTodoById(id);

                //If the item to delete is not present in database
                if (null == toDo)
                {
                    statusCode    = HttpStatusCode.NotFound;
                    statusMessage = AppConstants.Error;
                    Error error = new Error(string.Format(AppConstants.TODO_NOT_FOUND_MSG, id), AppConstants.TODO_NOT_FOUND);
                    errorlist.Add(error);
                }
                else
                {
                    // return value and check the status and handle error
                    // Database delete takes place here
                    if (_repository.remove(toDo) > 0)
                    {
                        statusCode    = HttpStatusCode.OK;
                        statusMessage = AppConstants.Success;
                    }
                    else
                    {
                        statusCode    = HttpStatusCode.InternalServerError;
                        statusMessage = AppConstants.Error;
                        errorlist.Add(new Error(AppConstants.DELETE_FAILED_MSG, AppConstants.DELETE_FAILED));
                    }
                }
            }
            catch (Exception ex)
            {
                statusCode    = HttpStatusCode.NotModified;
                statusMessage = AppConstants.Error;
                string strErrorMsg = AppConstants.Error_Message + ex.Message;
                Error  error       = new Error(strErrorMsg, AppConstants.TODO_DELETE_ERROR);
                errorlist.Add(error);
                Logger.WriteLog(AppConstants.Error_Message + ex.Message + AppConstants.Inner_Exception + ex.InnerException +
                                AppConstants.Stack_Trace + ex.StackTrace + AppConstants.Soure + ex.Source);
            }
            //Write to log file if error is present
            if (errorlist.Count > 0)
            {
                errorlist.ForEach(error => Logger.WriteLog(AppConstants.Error + " in DeleteToDo() for ID : " + id + AppConstants.Error_Code
                                                           + error.errorCode + AppConstants.Error_Message + error.errorMessage));
            }
            responseHeader.statusCode    = statusCode;
            responseHeader.statusMessage = statusMessage;
            responseHeader.error         = errorlist;
            todoResponse.responseHeader  = responseHeader;
            responseBody.todo            = _repository.getAllTodo();
            todoResponse.responseBody    = responseBody;
            return(todoResponse);
        }
Beispiel #34
0
 public void SetErrorBody(string msg, ResponseBody bdy = null)
 {
     success = false;
     message = msg;
     body    = bdy;
 }
Beispiel #35
0
        [HttpPost] // Routing by explicitly specifying the HTTP Action type in the header
        public TodoResponse AddNewToDo(ToDo toDo)
        {
            TodoResponse   todoResponse   = new TodoResponse();
            ResponseHeader responseHeader = new ResponseHeader();
            ResponseBody   responseBody   = new ResponseBody();
            HttpStatusCode statusCode;
            List <Error>   errorlist     = new List <Error>();
            string         statusMessage = string.Empty;

            errorlist = ValidateUtility.ValidateInput(toDo);

            try
            {
                if (!ModelState.IsValid)
                {
                    statusCode    = HttpStatusCode.BadRequest;
                    statusMessage = AppConstants.Error;
                    errorlist.Add(new Error(AppConstants.MODAL_STATE_INVALID, AppConstants.BAD_REQUEST));
                }

                //Check if any of the input parameters are empty
                else if (errorlist.Count > 0)
                {
                    statusCode    = HttpStatusCode.BadRequest;
                    statusMessage = AppConstants.Error;
                    errorlist.ForEach(e => Logger.WriteLog(e.errorMessage));
                }

                else
                {
                    // Check if the item with same descrition is already present
                    if (ValidateUtility.ToDoExists(_repository.getAllTodo(), toDo))
                    {
                        statusCode    = HttpStatusCode.Conflict;
                        statusMessage = AppConstants.Error;
                        Error error = new Error(AppConstants.TODO_ALREADY_EXIST_MSG, AppConstants.TODO_ALREADY_EXIST);
                        errorlist.Add(error);
                        Logger.WriteLog(AppConstants.TODO_ALREADY_EXIST_MSG);
                    }

                    //If item not present, then insert new data
                    else
                    {
                        // return value and check the status and handle error
                        // Database insertion takes place here
                        if (_repository.insert(toDo) > 0)
                        {
                            statusCode    = HttpStatusCode.OK;
                            statusMessage = AppConstants.Success;
                        }

                        // If database insertion failed then handle the exception
                        else
                        {
                            statusCode    = HttpStatusCode.InternalServerError;
                            statusMessage = AppConstants.Error;
                            errorlist.Add(new Error(AppConstants.INSERT_FAILED_MSG, AppConstants.INSERT_FAILED));
                        }
                    }
                }
            }
            catch (DbUpdateException dbEx)
            {
                //If To Do item is already present in database with same id
                if (ToDoIdExists(toDo.SlNo))
                {
                    statusCode    = HttpStatusCode.Conflict;
                    statusMessage = AppConstants.Error;
                    string strErrorMsg = AppConstants.Error_Message + dbEx.Message + AppConstants.Inner_Exception + dbEx.InnerException +
                                         AppConstants.Stack_Trace + dbEx.StackTrace + AppConstants.Soure + dbEx.Source;
                    Error error = new Error(AppConstants.TODO_ALREADY_EXIST_MSG, AppConstants.TODO_ALREADY_EXIST);
                    errorlist.Add(error);
                    Logger.WriteLog(strErrorMsg);
                }
                else
                {
                    statusCode    = HttpStatusCode.InternalServerError;
                    statusMessage = AppConstants.Error;
                    string strErrorMsg = AppConstants.Error_Message + dbEx.Message;
                    errorlist.Add(new Error(AppConstants.INTERNAL_SERVER_ERROR_MSG, AppConstants.INTERNAL_SERVER_ERROR));
                    Logger.WriteLog(AppConstants.Error_Message + strErrorMsg + AppConstants.Inner_Exception + dbEx.InnerException +
                                    AppConstants.Stack_Trace + dbEx.StackTrace + AppConstants.Soure + dbEx.Source);
                }
            }

            //Write to log file if error is present
            if (errorlist.Count > 0)
            {
                //foreach (var error in errorlist)
                //{
                //    Logger.WriteLog(AppConstants.Error + " in PostToDo() " +AppConstants.Error_Code
                //                   + error.errorCode + AppConstants.Error_Message + error.errorMessage);
                //}
                errorlist.ForEach(error => Logger.WriteLog(AppConstants.Error + " in PostToDo() " + AppConstants.Error_Code
                                                           + error.errorCode + AppConstants.Error_Message + error.errorMessage));
            }
            responseHeader.statusCode    = statusCode;
            responseHeader.statusMessage = statusMessage;
            responseHeader.error         = errorlist;
            todoResponse.responseHeader  = responseHeader;
            responseBody.todo            = _repository.getAllTodo();
            todoResponse.responseBody    = responseBody;
            return(todoResponse);
        }
Beispiel #36
0
        public TodoResponse PutToDo(int id, ToDo toDo)
        {
            TodoResponse   todoResponse   = new TodoResponse();
            ResponseHeader responseHeader = new ResponseHeader();
            ResponseBody   responseBody   = new ResponseBody();
            List <Error>   errorlist      = new List <Error>();
            HttpStatusCode statusCode;
            string         statusMessage = string.Empty;

            errorlist = ValidateUtility.ValidateInput(toDo);

            try
            {
                if (!ModelState.IsValid)
                {
                    statusCode    = HttpStatusCode.BadRequest;
                    statusMessage = AppConstants.Error;
                    errorlist.Add(new Error(AppConstants.MODAL_STATE_INVALID, AppConstants.BAD_REQUEST));
                }

                //Check if any of the input parameters are empty
                else if (errorlist.Count > 0)
                {
                    statusCode    = HttpStatusCode.BadRequest;
                    statusMessage = AppConstants.Error;
                    //add mulitple error if needed to errorlist
                    errorlist.ForEach(e => Logger.WriteLog(e.errorMessage));
                }

                // check if the ids in the request match
                else if (id != toDo.SlNo)
                {
                    statusCode    = HttpStatusCode.BadRequest;
                    statusMessage = AppConstants.Error;
                    //add mulitple error if needed to errorlist
                    errorlist.Add(new Error(AppConstants.TODO_ID_MISMATCH_MSG, AppConstants.TODO_ID_MISMATCH));
                }

                // Perform the Edit operation
                else
                {
                    // Database update
                    int result = _repository.save(toDo);
                    // return value and check the status and handle error
                    if (result > 0)
                    {
                        statusCode    = HttpStatusCode.OK;
                        statusMessage = AppConstants.Success;
                    }
                    else
                    {
                        statusCode    = HttpStatusCode.InternalServerError;
                        statusMessage = AppConstants.Error;
                        errorlist.Add(new Error(AppConstants.SAVE_FAILED_MSG, AppConstants.SAVE_FAILED));
                    }
                }
            }
            catch (DbUpdateConcurrencyException dbEx)
            {
                // If the Id for Deletion is not present in the database
                if (!ToDoIdExists(id))
                {
                    statusCode    = HttpStatusCode.NotFound;
                    statusMessage = AppConstants.Error;
                    string strErrorMsg = AppConstants.Error_Message + dbEx.Message;
                    errorlist.Add(new Error(strErrorMsg, AppConstants.TODO_NOT_FOUND));

                    Logger.WriteLog(AppConstants.Error_Message + strErrorMsg +
                                    AppConstants.Inner_Exception + dbEx.InnerException +
                                    AppConstants.Stack_Trace + dbEx.StackTrace + AppConstants.Soure + dbEx.Source);
                }
                else
                {
                    // This will be caught and handled in the ToDoCustomException handler
                    throw;
                }
            }

            //Write to log file if error is present
            if (errorlist.Count > 0)
            {
                errorlist.ForEach(error => Logger.WriteLog(AppConstants.Error + " in PutToDo() for ID : " + id + AppConstants.Error_Code
                                                           + error.errorCode + AppConstants.Error_Message + error.errorMessage));
            }
            responseHeader.statusCode    = statusCode;
            responseHeader.statusMessage = statusMessage;
            responseHeader.error         = errorlist;
            todoResponse.responseHeader  = responseHeader;
            responseBody.todo            = _repository.getAllTodo();
            todoResponse.responseBody    = responseBody;
            return(todoResponse);
        }
Beispiel #37
0
        public IActionResult GetMailSettingList()
        {
            var result = _mailSettingService.GetMailSetting();

            return(Ok(ResponseBody.From(result)));
        }
Beispiel #38
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="context"></param>
 /// <param name="body"></param>
 /// <returns></returns>
 protected byte[] ProcessResponse(IHttpRequestContext context, ResponseBody body)
 {
     return ResponseFormater.Serialize(body);
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="body"></param>
 /// <returns></returns>
 public byte[] Serialize(ResponseBody body)
 {
     string json = JsonUtils.SerializeCustom(body);
     var encoding = new UTF8Encoding();
     return encoding.GetBytes(json);
 }
Beispiel #40
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="body"></param>
        protected virtual void OnRequest(HttpContext context, ResponseBody body)
        {

        }
Beispiel #41
0
		/*
		 * A failure result with a full error message.
		 */
		public DebugResult(int id, string format, dynamic arguments = null) {
			Success = false;
			Body = new ErrorResponseBody(new Message(id, format, arguments));
		}
Beispiel #42
0
		public void SetErrorBody(string msg, ResponseBody bdy = null) {
			success = false;
			message = msg;
			body = bdy;
		}
Beispiel #43
0
        public override void Invoke(AMFContext context)
        {
            MessageOutput messageOutput = context.MessageOutput;

            for (int i = 0; i < context.AMFMessage.BodyCount; i++)
            {
                AMFBody amfBody = context.AMFMessage.GetBodyAt(i);

                if (!amfBody.IsEmptyTarget)
                {
                    continue;
                }

                object content = amfBody.Content;
                if (content is IList)
                {
                    content = (content as IList)[0];
                }
                IMessage message = content as IMessage;

                //Check for Flex2 messages and handle
                if (message != null)
                {
                    //if (FluorineContext.Current.Client == null)
                    //    FluorineContext.Current.SetCurrentClient(_endpoint.GetMessageBroker().ClientRegistry.GetClient(message));

                    if (message.clientId == null)
                    {
                        message.clientId = Guid.NewGuid().ToString("D");
                    }

                    //Check if response exists.
                    ResponseBody responseBody = messageOutput.GetResponse(amfBody);
                    if (responseBody != null)
                    {
                        continue;
                    }

                    try
                    {
                        if (context.AMFMessage.BodyCount > 1)
                        {
                            CommandMessage commandMessage = message as CommandMessage;
                            //Suppress poll wait if there are more messages to process
                            if (commandMessage != null && commandMessage.operation == CommandMessage.PollOperation)
                            {
                                commandMessage.SetHeader(CommandMessage.FluorineSuppressPollWaitHeader, null);
                            }
                        }
                        IMessage resultMessage = _endpoint.ServiceMessage(message);
                        if (resultMessage is ErrorMessage)
                        {
                            ErrorMessage errorMessage = resultMessage as ErrorMessage;
                            responseBody = new ErrorResponseBody(amfBody, message, resultMessage as ErrorMessage);
                            if (errorMessage.faultCode == ErrorMessage.ClientAuthenticationError)
                            {
                                messageOutput.AddBody(responseBody);
                                for (int j = i + 1; j < context.AMFMessage.BodyCount; j++)
                                {
                                    amfBody = context.AMFMessage.GetBodyAt(j);

                                    if (!amfBody.IsEmptyTarget)
                                    {
                                        continue;
                                    }

                                    content = amfBody.Content;
                                    if (content is IList)
                                    {
                                        content = (content as IList)[0];
                                    }
                                    message = content as IMessage;

                                    //Check for Flex2 messages and handle
                                    if (message != null)
                                    {
                                        responseBody = new ErrorResponseBody(amfBody, message, new SecurityException(errorMessage.faultString));
                                        messageOutput.AddBody(responseBody);
                                    }
                                }
                                //Leave further processing
                                return;
                            }
                        }
                        else
                        {
                            responseBody = new ResponseBody(amfBody, resultMessage);
                        }
                    }
                    catch (Exception exception)
                    {
                        if (log != null && log.IsErrorEnabled)
                        {
                            log.Error(exception.Message, exception);
                        }
                        responseBody = new ErrorResponseBody(amfBody, message, exception);
                    }
                    messageOutput.AddBody(responseBody);
                }
            }
        }
Beispiel #44
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="context"></param>
 /// <param name="body"></param>
 protected abstract void OnRequest(HttpContext context, ResponseBody body);
Beispiel #45
0
 public void Write(ArraySegment <byte> data)
 {
     ResponseBody.Write(data.Array, data.Offset, data.Count);
 }
 public static CanFulfillResponseBody CanFulfill(this ResponseBody body, CanFulfillIntent intent)
 {
     return(new CanFulfillResponseBody(body, intent));
 }
        public IActionResult GetTransferRoles()
        {
            var roles = _roleService.GetTransferRoles();

            return(Ok(ResponseBody.From(roles)));
        }