private OMVSD.OSD GetHandler(RestHandler handler, Uri uri, String after) { OMVSD.OSDMap ret = new OMVSD.OSDMap(); string lastDate = "xx"; lock (m_chats) { while (m_chats.Count > 0) { ChatEntry ce = m_chats.Dequeue(); string dateString = ce.time.ToString("yyyyMMddhhmmssfff"); OMVSD.OSDMap chat = new OMVSD.OSDMap(); chat.Add("Time", new OMVSD.OSDString(dateString)); chat.Add("From", new OMVSD.OSDString(ce.fromName)); chat.Add("Message", new OMVSD.OSDString(ce.message)); chat.Add("Type", new OMVSD.OSDString(ce.chatTypeString)); chat.Add("EntryType", new OMVSD.OSDString(ChatEntryTypeString[(int)ce.chatEntryType])); chat.Add("Position", new OMVSD.OSDString(ce.position.ToString())); if (ce.ownerID != null) { chat.Add("OwnerID", new OMVSD.OSDString(ce.ownerID.ToString())); } while (ret.ContainsKey(dateString)) { dateString += "1"; } ret.Add(dateString, chat); lastDate = dateString; } } return(ret); }
public PingResult TryPingServer() { return(Try(() => RestHandler.RetryPolicy().ExecuteAsync(() => handler.Get(env.Host, env.Uri))) .Map(r => r.Result.Content.ReadAsStringAsync().Result) .Filter(r => r.Contains("build")) .Match(Succ: ToPingResponse(), Fail: ToNetworkFailure())); }
private async void Button_Click(object sender, RoutedEventArgs e) { //var viewModel = (FtpSettingsViewModels)ViewModel; //var lst = (await viewModel.Connect()).ToList(); //await viewModel.FTP.ChangeDirectoryAsync("/media/data/apps"); //var lst2 = (await viewModel.FTP.List()).ToList(); //Console.WriteLine(lst2.Count()); var rs = new RestHandler(); var games = rs.GetGameByName("Alundra 2"); foreach (var game in games.Data.Games) { if (game.GameTitle == "Alundra") { var bxArt = games.Include.Boxarts.data.FirstOrDefault(b => b.Key == game.Id); //var id = game.Id; //var img = rs.GetGameImage(id); var baseUrl = games.Include.Boxarts.BaseUrl.Thumb; //var path = img.Data.Images.FirstOrDefault(i => i.Type == "boxart"); //Console.WriteLine(baseUrl + path.Filename); ImgBrowser.Source = new Uri(baseUrl + bxArt.Value.First(i => i.Side == "front").Filename); } } }
public Task Does_Not_Throws_UnhandledResponseException_If_Code_Handled(HttpStatusCode code) { IRestHandler handler = new RestHandler(CreateRequest(code), _deserializerFactory); handler.RegisterCallback(code, () => { }); return(handler.HandleAsync()); }
void PostAcquireRequestState(object sender, EventArgs e) { // The PostAcquireRequestState event is raised after the session data has been obtained. // If the request is for a class that implements System.Web.UI.Page and it is a rest // method call, the WebServiceData class (that was explained in a previous post) is used // to call the requested method from the Page. After the method has been called, // the CompleteRequest method is called, bypassing all pipeline events and executing // the EndRequest method. This allows MS AJAX to be able to call a method on a page // instead of having to create a web service to call a method. HttpApplication app = (HttpApplication)sender; HttpContext context = app.Context; if (context == null) { return; } HttpRequest request = context.Request; string contentType = request.ContentType; IHttpHandler currentHandler = context.CurrentHandler; if (currentHandler == null) { return; } Type pageType = currentHandler.GetType(); if (typeof(Page).IsAssignableFrom(pageType) && !String.IsNullOrEmpty(contentType) && contentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)) { IHttpHandler h = RestHandler.GetHandler(context, pageType, request.FilePath); h.ProcessRequest(context); app.CompleteRequest(); } }
/// <summary> /// Posting to this communication instance. The URI comes in as "/api/MYNAME/ACTION" where /// ACTION is "login", "logout". /// </summary> /// <param name="uri"></param> /// <param name="body"></param> /// <returns></returns> public OMVSD.OSD ProcessPost(RestHandler handler, Uri uri, string after, OMVSD.OSD body) { OMVSD.OSDMap ret = new OMVSD.OSDMap(); if (m_comm == null) { m_log.Log(LogLevel.DBADERROR, "POST WITHOUT COMM CONNECTION!! URL=" + uri.ToString()); return(new OMVSD.OSD()); } m_log.Log(LogLevel.DCOMMDETAIL, "Post action: {0}", uri.ToString()); switch (after) { case "/login": ret = PostActionLogin(body); break; case "/teleport": ret = PostActionTeleport(body); break; case "/logout": ret = PostActionLogout(body); break; case "/exit": ret = PostActionExit(body); break; default: m_log.Log(LogLevel.DBADERROR, "UNKNOWN ACTION: " + uri.ToString()); ret.Add(RestHandler.RESTREQUESTERRORCODE, new OMVSD.OSDInteger(1)); ret.Add(RestHandler.RESTREQUESTERRORMSG, new OMVSD.OSDString("Unknown action")); break; } return(ret); }
public void ProcessRequestInvokes() { ServerConfig config = new ServerConfig(); ServerConfig_Accessor a = ServerConfig_Accessor.AttachShadow(config); ServerConfig_Accessor.m_instance = config; XmlDocument d = new XmlDocument(); d.LoadXml(string.Format("<restServices><Assemblies><add name=\"{0}\" /></Assemblies></restServices>", this.GetType().Assembly.GetName().Name)); RestConfig_Accessor restConfig = new RestConfig_Accessor(d); a.Rest = restConfig; IHttpHandler target = new RestHandler(); RestHandler_Accessor ra = RestHandler_Accessor.AttachShadow(target); HttpWorkerRequestMock r = new HttpWorkerRequestMock(); r.HttpVerb = "GET"; r.UriPath = "/directory/path/blah"; HttpContext context = new HttpContext(r, true); HttpContext_Accessor hca = HttpContext_Accessor.AttachShadow(context); RestServiceMock.Clear(); target.ProcessRequest(context); Assert.IsTrue(RestServiceMock.Instantiated); MethodInfo expected = typeof(RestServiceMock).GetMethod("GetSomething"); Assert.AreEqual(expected, RestServiceMock.Invoked); }
protected async void LoadEvents(object sender, EventArgs e) { PortCallMessageGrouper pcmg = new PortCallMessageGrouper(); callID = Request.QueryString["portCallID"]; List <portCallMessage> list; if (!string.IsNullOrEmpty(callID)) { list = await RestHandler.getEvents(callID); vesselDDList.SelectedValue = callID; Isreadonly.SetValue(Request.QueryString, false, null); Request.QueryString.Clear(); } else { list = await RestHandler.getEvents(vesselDDList.SelectedItem.Value); } pcmg = new PortCallMessageGrouper(list); eventListBox.DataSource = pcmg.getGroups(); eventListBox.DataBind(); }
protected async void addNewShip(object sender, EventArgs e) { string imoAndName = Request.Form[addShipDropDown.UniqueID]; string[] imoAndNameSplit = imoAndName.Split(' '); string addImo = imoAndNameSplit[0]; if (shipImosNames.Exists(obj => obj == imoAndName)) { DataBaseHandler.activateShip(addImo); } else { string result = await RestHandler.createPortCall(addImo); string[] resultlist = result.Split('"'); string portCallId = resultlist[3]; Vessel v = await RestHandler.getVesselByImo(addImo); DataBaseHandler.addShip(v, portCallId); Console.WriteLine(v.name); } Console.WriteLine("addNewShip before setdatatables"); setDataTables(); }
// Entry point for HttpListener public static RestHandler GetHandler(IHttpRequest httpReq, ILogger logger) { var pathInfo = httpReq.PathInfo; var pathParts = pathInfo.TrimStart('/').Split('/'); if (pathParts.Length == 0) { logger.Error("Path parts empty for PathInfo: {0}, Url: {1}", pathInfo, httpReq.RawUrl); return(null); } string contentType; var restPath = RestHandler.FindMatchingRestPath(httpReq.HttpMethod, pathInfo, out contentType); if (restPath != null) { return new RestHandler { RestPath = restPath, RequestName = restPath.RequestType.GetOperationName(), ResponseContentType = contentType } } ; return(null); } }
protected async void Page_Load(object sender, EventArgs e) { List <PortCall> portCallList = await RestHandler.getPortCalls(); messageRepeater.DataSource = portCallList; messageRepeater.DataBind(); }
public Task Throws_DeserializationException_When_Typed_Callback_Invoked_But_Content_Not_Presented(HttpStatusCode code) { IRestHandler handler = new RestHandler(CreateRequest(code), _deserializerFactory); handler.RegisterCallback(code, (object list) => { }); return(Assert.ThrowsAsync <DeserializationException>(() => handler.HandleAsync())); }
public void Can_parse_Ips() { var handler = new RestHandler(); var result = handler.GetEndpointAttributes(CreateRequest("204.2.145.235")); Assert.That(result.Has(EndpointAttributes.External)); Assert.That(result.Has(EndpointAttributes.HttpGet)); Assert.That(result.Has(EndpointAttributes.InSecure)); }
// Entry point for HttpListener and .NET Core public static IHttpHandler GetHandler(IHttpRequest httpReq) { var appHost = HostContext.AppHost; foreach (var rawHttpHandler in appHost.RawHttpHandlersArray) { var handler = rawHttpHandler(httpReq); if (handler != null) { return(handler); } } var mode = appHost.Config.HandlerFactoryPath; var pathInfo = httpReq.PathInfo; //Default Request / if (string.IsNullOrEmpty(pathInfo) || pathInfo == "/") { RestPath matchesFallback = appHost.Config.FallbackRestPath?.Invoke(httpReq); if (matchesFallback == null || matchesFallback.Priority > 0 || (matchesFallback.MatchRule == null && !(matchesFallback.Priority < 0))) // is not targeted fallback { //e.g. to Process View Engine requests var catchAllHandler = GetCatchAllHandlerIfAny(appHost, httpReq.HttpMethod, pathInfo, httpReq.GetPhysicalPath()); if (catchAllHandler != null) { return(catchAllHandler); } } //If the fallback route can handle it, let it if (matchesFallback != null) { var sanitizedPath = RestHandler.GetSanitizedPathInfo(pathInfo, out var contentType); return(new RestHandler { RestPath = matchesFallback, RequestName = matchesFallback.RequestType.GetOperationName(), ResponseContentType = contentType }); } if (mode == null) { return(DefaultHttpHandler); } if (DefaultRootFileName != null) { return(StaticFilesHandler); } return(NonRootModeDefaultHttpHandler); } return(GetHandlerForPathInfo(httpReq, httpReq.GetPhysicalPath()) ?? NotFoundHttpHandler); }
public void Not_Invoke_Callback_Without_Handler_Execution(HttpStatusCode code) { bool act = false; IRestHandler handler = new RestHandler(CreateRequest(code), _deserializerFactory); handler.RegisterCallback(code, (object content) => act = true); Assert.False(act); }
protected async void sendMessage(object sender, EventArgs e) { ScriptManager.RegisterStartupScript(Page, typeof(Page), "fancyboxscript", "$('.fancyBoxButton').click();", true); Task <portCallMessage> pcmTask = genMessage(); var pcm = await pcmTask; string response = await RestHandler.createPCM(pcm); loadingText.Text = response; messageSentButton.Visible = true; }
private async void bindPortLocation(DropDownList locationType, DropDownList locationsddl) { List <PortLocation> locations = await RestHandler.getLocations(); locations = locations.Where(x => x.URN.Contains(locationType.SelectedValue)).ToList(); locationsddl.DataSource = locations; locationsddl.DataTextField = "name"; locationsddl.DataValueField = "URN"; locationsddl.DataBind(); }
public async Task Invoke_Untyped_Callback_When_Content_Not_Presented(HttpStatusCode code) { bool act = false; IRestHandler handler = new RestHandler(CreateRequest(code), _deserializerFactory); handler.RegisterCallback(code, () => act = true); await handler.HandleAsync(); Assert.True(act); }
/// <summary> /// Called when bot client is no longer used by any client and can be shutdown. /// </summary> internal void ShutdownBot() { Logger.Debug($"{nameof(BotClient)}.{nameof(ShutdownBot)} Shutting down the bot"); ActiveBots.Remove(Settings.ApiToken); Initialized = false; _webSocket?.Shutdown(); _webSocket = null; Rest?.Shutdown(); Rest = null; ReadyData = null; }
// Entry point for HttpListener and .NET Core public static IHttpHandler GetHandler(IHttpRequest httpReq) { var appHost = HostContext.AppHost; foreach (var rawHttpHandler in appHost.RawHttpHandlersArray) { var handler = rawHttpHandler(httpReq); if (handler != null) { return(handler); } } var mode = appHost.Config.HandlerFactoryPath; var pathInfo = httpReq.PathInfo; //Default Request / if (string.IsNullOrEmpty(pathInfo) || pathInfo == "/") { //If the fallback route can handle it, let it RestPath restPath = appHost.Config.FallbackRestPath?.Invoke(httpReq); if (restPath != null) { var sanitizedPath = RestHandler.GetSanitizedPathInfo(pathInfo, out var contentType); return(new RestHandler { RestPath = restPath, RequestName = restPath.RequestType.GetOperationName(), ResponseContentType = contentType }); } //e.g. CatchAllHandler to Process Markdown files var catchAllHandler = GetCatchAllHandlerIfAny(appHost, httpReq.HttpMethod, pathInfo, httpReq.GetPhysicalPath()); if (catchAllHandler != null) { return(catchAllHandler); } if (mode == null) { return(DefaultHttpHandler); } if (DefaultRootFileName != null) { return(StaticFilesHandler); } return(NonRootModeDefaultHttpHandler); } return(GetHandlerForPathInfo(httpReq, httpReq.GetPhysicalPath()) ?? NotFoundHttpHandler); }
public void Throws_binding_exception_when_unable_to_bind_request() { var path = "/request/{id}/path"; var request = ConfigureRequest(path); var response = new Mock<IHttpResponse>().Object; var handler = new RestHandler { RestPath = new RestPath(typeof(RequestType), path) }; Assert.Throws<RequestBindingException>(() => handler.ProcessRequest(request, response, string.Empty)); }
public void Does_add_CustomAttributes_to_when_added_in_AppHost_constructor() { var restPath = RestHandler.FindMatchingRestPath("GET", "/custom-register", out _); Assert.That(restPath, Is.Not.Null); Assert.That(restPath.RequestType, Is.EqualTo(typeof(Register))); //Allows JSON appHost.ServiceController.AssertServiceRestrictions(typeof(Register), RequestAttributes.Json); Assert.Throws <UnauthorizedAccessException>(() => appHost.ServiceController.AssertServiceRestrictions(typeof(Register), RequestAttributes.Xml)); }
// IModule.AfterAllModulesLoaded public virtual bool AfterAllModulesLoaded() { LogManager.Log.Log(LogLevel.DINIT, "AvatarTracker.AfterAllModulesLoaded()"); m_restHandler = new RestHandler("/avatars", GetHandler, PostHandler); m_world = World.Instance; // there is only one world m_world.OnAgentNew += new WorldAgentNewCallback(World_OnAgentNew); m_world.OnAgentRemoved += new WorldAgentRemovedCallback(World_OnAgentRemoved); m_world.OnWorldEntityNew += new WorldEntityNewCallback(World_OnWorldEntityNew); m_world.OnWorldEntityUpdate += new WorldEntityUpdateCallback(World_OnWorldEntityUpdate); m_world.OnWorldEntityRemoved += new WorldEntityRemovedCallback(World_OnWorldEntityRemoved); return(true); }
protected async void Page_Load(object sender, EventArgs e) { portLocations = await RestHandler.getLocations(); if (!(this.IsPostBack)) { LoadList(); LoadEvents(sender, e); //StartTime(); } }
public async Task <IActionResult> PostTransaction([FromBody] VendRequest req) { _logger.LogInformation($"{req?.RechargeType} purchase request for {req?.PhoneNumber} NGN{req?.Amount}"); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } //persist request var rechargeType = req.RechargeType.ParseEnum <RechargeType>(); var serviceCode = await _context.ServiceCodes.FirstOrDefaultAsync(x => x.RechargeType == rechargeType && x.NetworkType == req.NetworkType.ParseEnum <NetworkType>()); var reqTrans = TransactionService.GetTransaction(req, rechargeType, serviceCode?.Code); _context.RechargeTransactions.Add(reqTrans); await _context.SaveChangesAsync(); _logger.LogInformation("Transaction request persisted."); //initate service call var switchReq = CreditSwitchService.GetRequest(reqTrans, _config); CreditSwitchRespose switchResp = null; try { switchResp = await RestHandler.PostJsonAsync <CreditSwitchRespose>(_config.BaseUrl, _config.AirtimePath, switchReq); if (switchResp == null) { _logger.LogWarning("Switch response is null"); return(BadRequest(TransactionService.GetFailureResponse(req))); } } catch (Exception e) { _logger.LogError(e, "Web service request failed."); return(BadRequest(TransactionService.GetFailureResponse(req))); } //persist response var respTrans = TransactionService.GetTransaction(switchResp, switchReq, rechargeType); _context.RechargeTransactions.Add(respTrans); await _context.SaveChangesAsync(); _logger.LogInformation("Response transaction was persisted successfully."); var resp = TransactionService.GetResponse(switchResp, switchReq, req.DealerCode, null); return(Ok(resp)); }
private T StringToPoco <T>(string str) { using (new BasicAppHost().Init()) { NameValueCollection queryString = HttpUtility.ParseQueryString(str); var restPath = new RestPath(typeof(T), "/query", "GET, POST"); var restHandler = new RestHandler(); var httpReq = new MockHttpRequest("query", "GET", "application/json", "query", queryString, new MemoryStream(), new NameValueCollection()); httpReq.SetRoute(restPath); var request = (T)restHandler.CreateRequestAsync(httpReq, "query").Result; return(request); } }
public bool TryConvertArgument(RestHandler context, string value, out object result) { //Make sure the ticket is valid long ticket; if (!long.TryParse(value, out ticket)) { result = null; return(false); } //Get the ban result = context.Starbound.Configurator.GetBanAsync(ticket).Result; return(true); }
private T StringToPoco <T>(string str) { var testAppHost = new TestAppHost(new Container(), GetType().Assembly); NameValueCollection queryString = HttpUtility.ParseQueryString(str); var restPath = new RestPath(typeof(T), "/query", "GET, POST"); var restHandler = new RestHandler() { RestPath = restPath }; var httpReq = new HttpRequestMock("query", "GET", "application/json", "query", queryString, new MemoryStream(), new NameValueCollection()); var request = (T)restHandler.CreateRequest(httpReq, "query"); return(request); }
public void Throws_binding_exception_when_unable_to_bind_request() { var path = "/request/{id}/path"; var request = ConfigureRequest(path); var response = new Mock <IHttpResponse>().Object; ConfigureHost(); var handler = new RestHandler { RestPath = new RestPath(typeof(RequestType), path) }; Assert.Throws <RequestBindingException>(() => handler.ProcessRequest(request, response, string.Empty)); }
public async Task Throws_binding_exception_when_unable_to_bind_request() { var path = "/request/{id}/path"; var request = ConfigureRequest(path); var response = request.Response; var handler = new RestHandler { RestPath = new RestPath(typeof(RequestType), path) }; await handler.ProcessRequestAsync(request, response, string.Empty); Assert.That(response.StatusCode, Is.EqualTo(400)); }
public bool TryConvertArgument(RestHandler context, string value, out object result) { //Make sure the connection ID is valid int cid; if (!int.TryParse(value, out cid)) { result = null; return(false); } //Get the player. result = context.Starbound.Connections.GetPlayer(cid); return(true); }
public void Can_deserialize_TestRequest_QueryStringSerializer_output() { // Setup new BasicAppHost(new Container(), typeof(TestService).Assembly).Init(); var restPath = new RestPath(typeof(TestRequest), "/service", "GET"); var restHandler = new RestHandler { RestPath = restPath }; var requestString = "ListOfA={ListOfB:[{Property:prop1},{Property:prop2}]}"; NameValueCollection queryString = HttpUtility.ParseQueryString(requestString); var httpReq = new MockHttpRequest("service", "GET", "application/json", "service", queryString, new MemoryStream(), new NameValueCollection()); var request2 = (TestRequest)restHandler.CreateRequest(httpReq, "service"); Assert.That(request2.ListOfA.Count, Is.EqualTo(1)); Assert.That(request2.ListOfA.First().ListOfB.Count, Is.EqualTo(2)); }
public void Throws_binding_exception_when_unable_to_bind_request() { var path = "/request/{id}/path"; var request = ConfigureRequest(path); var response = new Mock<IHttpResponse>().Object; var handler = new RestHandler { RestPath = new RestPath(typeof(RequestType), path) }; try { handler.ProcessRequestAsync(request, response, string.Empty).Wait(); Assert.Fail("Should throw SerializationException"); } catch (AggregateException aex) { Assert.That(aex.InnerExceptions.Count, Is.EqualTo(1)); Assert.That(aex.InnerException.GetType().Name, Is.EqualTo("SerializationException")); } }
public void Throws_binding_exception_when_unable_to_match_path_values() { var path = "/request/{will_not_match_property_id}/pathh"; var request = ConfigureRequest(path); var response = new Mock<IHttpResponse>().Object; var handler = new RestHandler { RestPath = new RestPath(typeof(RequestType), path) }; try { handler.ProcessRequestAsync(request, response, string.Empty).Wait(); Assert.Fail("Should throw RequestBindingException"); } catch (AggregateException aex) { Assert.That(aex.InnerExceptions.Count, Is.EqualTo(1)); Assert.That(aex.InnerException is RequestBindingException); } }