private RegionResultModel BuildRegionResultModel(string hashes, bool isPointSet) { var jobManager = WebApiApplication.GetSharedJobManager(HttpContext); JobStatus[] stats = HttpUtility.UrlDecode(hashes).Split(',').Select(h => jobManager.GetStatus(h)).ToArray(); if (stats.All(s => s.State == JobOrPartState.Failed)) { return(new RegionResultModel(RegionResultStatus.Failed, null, isPointSet)); } else if (stats.All(s => s.State == JobOrPartState.Pending)) { return(new RegionResultModel(RegionResultStatus.Pending, stats.Min(s => s.PendingCount), isPointSet)); } else if (stats.All(s => s.State == JobOrPartState.Completed)) { return(new RegionResultModel(RegionResultStatus.Succeeded, hashes, isPointSet)); } else if (stats.All(s => s.State == JobOrPartState.Completed || s.State == JobOrPartState.Failed)) { return(new RegionResultModel(RegionResultStatus.PartiallySucceeded, hashes, isPointSet)); } else { var prg = stats.Where(s => s.State == JobOrPartState.InProgress).ToArray(); var completedCount = stats.Where(s => s.State == JobOrPartState.Completed).Count(); var otherCount = stats.Where(s => s.State != JobOrPartState.Completed && s.State != JobOrPartState.InProgress).Count(); return(new RegionResultModel(RegionResultStatus.InProgress, (prg.Select(s => s.ProgressPercent).Sum() + 100 * completedCount) / (prg.Length + completedCount + otherCount), isPointSet)); } }
// GET api/Configuration public Microsoft.Research.Science.FetchClimate2.Serializable.FetchConfiguration Get() { var configuration = WebApiApplication.GetFetchConfiguration(DateTime.MaxValue); var toSerizlize = new Microsoft.Research.Science.FetchClimate2.Serializable.FetchConfiguration(configuration); return(toSerizlize); }
public HttpResponseMessage Get(string playlistId, string pageToken = "") { if (!RequestProtection.AddRequest(WebApiApplication.GetClientIp(), RequestType.PlaylistRequest)) { return(Request.CreateResponse(HttpStatusCode.Forbidden, "Usage limit exceeded")); } try { var client = new RestClient("https://www.googleapis.com"); var request = new RestRequest("/youtube/v3/playlistItems", Method.GET); request.AddParameter("key", Properties.Settings.GoogleApiKey); request.AddParameter("part", "snippet"); request.AddParameter("playlistId", playlistId); request.AddParameter("maxResults", 50); request.AddParameter("pageToken", pageToken); var response = client.Execute(request); return(Request.CreateResponse(response.StatusCode, JObject.Parse(response.Content))); } catch { // ignored } return(Request.CreateResponse(HttpStatusCode.InternalServerError)); }
public void GetShadowCopyPath_ReturnsExpectedPath(string currentShadowCopy, string scriptPath, string expected) { string updatedPath = WebApiApplication.GetShadowCopyPath(currentShadowCopy, scriptPath); string expectedPath = string.Join(";", new[] { currentShadowCopy, scriptPath }.Where(s => !string.IsNullOrEmpty(s))); Assert.Equal(expectedPath, updatedPath); }
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result) { var activity = await result as Activity; if (activity.Text == "help") { await ShowHelp(context); } else { ILifetimeScope scope = WebApiApplication.GetContainer(); try { IDialogCreator obj = scope.ResolveNamed <IDialogCreator>(activity.Text); context.Call(obj.CreateNewDialog(context), AfterDialog); } catch (Exception err) { await context.PostAsync(err.Message); await context.PostAsync("I don't understand"); context.Wait(MessageReceivedAsync); } } }
public void Start() { // start a thread and start doing some processing Console.WriteLine("Thread started, processing.."); using (var app = new WebApiApplication()) { Console.WriteLine("Work path: " + Config.Pathes.Work); Console.WriteLine("Writing in work path: " + (Config.Pathes.WriteAllow ? "allowed" : "DENIED")); Console.WriteLine("Admin rights: " + (Config.AdminRights ? "yes" : "no")); Console.WriteLine("Init server... Base address: " + app.Address); app.Run(); // Create HttpCient and make a request to api/values //HttpClient client = new HttpClient(); //var response = client.GetAsync(baseAddress + "api/values").Result; //Console.WriteLine(response); //Console.WriteLine(response.Content.ReadAsStringAsync().Result); Console.WriteLine("Listening..."); while (!exitSystem) { } } }
public IHttpActionResult GetEqDetail() { ArrayList arrayList = new ArrayList(); foreach (var item in dic_Sockets.Values) { string msgId = Guid.NewGuid().ToString();//定义一个标识,标识这个请求,设备回应的数据应该带上 var obj = new { msgId, url = "queryDeviceDetail" }; item.socket.Send(JsonConvert.SerializeObject(obj)); JObject jObject = null; for (int i = 0; i < 7; i++) //循环去内存中查找有没有回应 { Thread.Sleep(200); jObject = WebApiApplication.GetCache(msgId) as JObject; if (jObject != null) { if (jObject["errCode"].ToString() == "0") { arrayList.Add(jObject["productModel"].ToString()); } else { return(this.ErrorData(jObject["errMsg"].ToString())); } } else { continue; } } } return(this.SendData(arrayList)); }
// GET api/Status?hash=blobHash public string Get(string hash) { var jobManager = WebApiApplication.GetSharedJobManager(Request); var status = jobManager.GetStatus(hash).ToString(); FrontendTrace.TraceVerbose("{0}: Reporting status {1}", hash, status); return(status); }
public static void Connect() { dic_Sockets = new Dictionary <string, WebSocketViewModel>(); WebSocketServer server = new WebSocketServer("ws://0.0.0.0:9527");//监听所有的的地址 WebSocketViewModel socketViewModel = new WebSocketViewModel(); //出错后进行重启 server.RestartAfterListenError = true; server.Start(socket => { socket.OnOpen = () => //连接建立事件 { //获取客户端网页的url string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort; socketViewModel.socket = socket; socketViewModel.IP = clientUrl; dic_Sockets.Add(clientUrl, socketViewModel); LogTool.Write("|服务器:和客户端网页:" + clientUrl + " 建立WebSock连接!" + "当前连接数量:" + dic_Sockets.Count); }; socket.OnClose = () => //连接关闭事件 { string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort; //如果存在这个客户端,那么对这个socket进行移除 if (dic_Sockets.ContainsKey(clientUrl)) { //注:Fleck中有释放 //关闭对象连接 //if (dic_Sockets[clientUrl] != null) //{ //dic_Sockets[clientUrl].Close(); //} dic_Sockets.Remove(clientUrl); } LogTool.Write("|服务器:和客户端网页:" + clientUrl + " 断开WebSock连接!"); }; socket.OnMessage = message => //接受客户端网页消息事件 { string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort; JObject ResponObj = JsonConvert.DeserializeObject <JObject>(message); if (ResponObj != null) { if (ResponObj["msgId"] != null) //把设备发送的数据缓存起来,时长30秒 { WebApiApplication.SetCache(ResponObj["msgId"].ToString(), ResponObj, 30); } if (ResponObj["url"] != null) { if (ResponObj["url"].ToString() == "login") { socketViewModel.deviceSerial = ResponObj["deviceSerial"].ToString(); var obj = new { msgId = ResponObj["msgId"].ToString(), errCode = 0, errMsg = "success" }; socket.Send(JsonConvert.SerializeObject(obj)); } } } LogTool.WriteData("|服务器:【收到】来客户端:" + clientUrl + "的信息:\n" + message); }; }); }
public HttpServerFixture() { var config = new HttpConfiguration(); WebApiApplication.Configure(config); config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; config.EnsureInitialized(); _httpServer = new HttpServer(config); }
public void SetupWebApi() { WebApiApplication = new WebApiApplication() { WebApiConfiguration = EngineConfiguration.WebApi, ContainerResolver = new ContainerResolver(Container) }; WebApiApplication.Start(); }
public void TestFixtureSetUp() { // Initialize Autofac for dependency injection. AutofacRegistrations.RegisterDaoFactory(); Scope = AutofacRegistrations.Container.BeginLifetimeScope(); DaoFactory = Scope.Resolve <IDaoFactory>(); // Initialize AutoMapper with Streamus' server mappings. WebApiApplication.CreateAutoMapperMaps(); }
protected override void OnStart(string[] args) { try { app = new WebApiApplication(); app.Run(); } catch (Exception ex) { Catch.Set(ex); } base.OnStart(args); }
/// <summary> /// Start in-memory hosting server /// </summary> /// <returns>HttpServer instance</returns> public static HttpServer StartServer() { HttpConfiguration config = new HttpConfiguration(); WebApiApplication.Configure(config); config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; var server = new HttpServer(config); return(server); }
private RouteData GetRouteDataWithMockContext(string route, string httpMethod) { var routes = new RouteCollection(); WebApiApplication.RegisterRoutes(routes); var mockContext = new Mock <HttpContextBase>(); mockContext.Setup(x => x.Request.AppRelativeCurrentExecutionFilePath).Returns(route); mockContext.Setup(x => x.Request.HttpMethod).Returns(httpMethod); return(routes.GetRouteData(mockContext.Object)); }
public void Dispose() { if (WebApiApplication != null) { WebApiApplication.Dispose(); } if (MessageQueueListenerManager != null) { MessageQueueListenerManager.Dispose(); } }
// GET: api/InfoGet/{id} //This API call is client oriented: calls for the deployed Web App and manages a read only request. //This API is responsible for returning the counter size to the requesting client. public string Get(string id) { //string representation of output string output = ""; //get an SQL connection instance SqlConnection sql = WebApiApplication.getSQL(); //try and read the entries from the table SqlDataReader myReader = null; try { //get relevant row from table according to given ID SqlCommand myCmd = new SqlCommand("select * from CounterU where ID = @id", sql); myCmd.Parameters.AddWithValue("@id", id); try { myReader = myCmd.ExecuteReader(); } catch (Exception e) { if (myReader != null) { myReader.Close(); } myCmd.Dispose(); return(e.Message); } //read the content of the data reader myReader.Read(); //format the output string to contain Pi ID and counter value output = myReader["Label"].ToString() + " : " + myReader["line"].ToString(); //dispose all used resources myReader.Close(); myCmd.Dispose(); return(output); } //An error occured while retrieving data from sql table catch (Exception e) { if (myReader != null) { myReader.Close(); } return(e.Message); } }
//private PviAplication _application; public void Start() { WebApiApplication.Start(); var pviApp = WebApiApplication.PviApp; var factory = new TaskFactory(); factory.StartNew(() => pviApp.Connect(), TaskCreationOptions.LongRunning); //WebApiApplication.Start(); }
// Common code for all requests IHttpActionResult Common(string method, string database, string name, string id, KeyValuePair <string, string>[] query = null, string jsonbody = null) { var gateway = WebApiApplication.GetGateway(database); var ret = (gateway == null) ? Result.Failure("database not found: " + database) : gateway.JsonCall(method, name, id, query, jsonbody); if (ret.Ok) { return(Ok(ret.Value)); } return(BadRequest(ret.Message)); }
public void BeforeEachTest() { WebApiApplication.InitializeAutoMapper(); questionController = new QuestionController(); resultController = new ResultController(); responseOptionController = new ResponseOptionController(); repository = new TestQuestionRepository(); responseOptionController.QuestionRepository = repository; resultController.QuestionRepository = repository; questionController.QuestionRepository = repository; }
public async Task <HttpResponseMessage> Post([FromBody] CrashReport report) { var ip = WebApiApplication.GetClientIp(); if (!RequestProtection.AddRequest(ip, RequestType.CrashReport)) { return(Request.CreateResponse(HttpStatusCode.Forbidden, "Usage limit exceeded")); } var issueId = await GitHubReporter.CreateIssue(ip, report); return(MailReporter.SendMail(ip, report, issueId) ? Request.CreateResponse(HttpStatusCode.OK, "Success") : Request.CreateResponse(HttpStatusCode.InternalServerError, "Error sending message")); }
//sql_handler(string cmd): simple sql execute method << receives an sql command >> executes command on open sql connection public void sql_handler(string cmd) { SqlCommand myCommand = new SqlCommand(cmd, WebApiApplication.getSQL()); try { myCommand.ExecuteNonQuery(); } catch { return; } }
void Exit() { try { if (app == null) { return; } Worker.Instance.PauseSearch(); app.Dispose(); app = null; } catch (Exception ex) { Catch.Set(ex); } }
public void PagingApiRoute_CollaborationSpaces_ControllerMatch() { var config = new HttpConfiguration(); var routes = new RouteCollection(); WebApiApplication.RegisterRoutes(routes, config); var apiRouteData = config.Routes.GetRouteData(new HttpRequestMessage(HttpMethod.Post, "http://someurl/api/CollaborationSpaces/Page/1/Title")); Assert.IsNotNull(apiRouteData); Assert.AreEqual("CollaborationSpaces", apiRouteData.Values["controller"]); }
public void PagingApiRoute_FooAsSortExpression_IsNotMatch() { var config = new HttpConfiguration(); var routes = new RouteCollection(); WebApiApplication.RegisterRoutes(routes, config); var apiRouteData = config.Routes.GetRouteData(new HttpRequestMessage(HttpMethod.Get, "http://someurl/api/CollaborationSpaces/Page/2/Foo")); Assert.IsNull(apiRouteData); }
public void Start() { Logger.Log(new LogEntry(LoggingEventType.Information, "Host: Start")); var locator = new TypeRepository(); var pviApp = locator.GetInstance <IPviProcessor>(); var factory = new TaskFactory(); factory.StartNew(() => pviApp.Connect(), TaskCreationOptions.LongRunning); WebApiApplication.Locator = locator; WebApiApplication.Logger = Logger; WebApiApplication.Start(); }
public static void Register(HttpConfiguration config) { //// Uncomment the following to use the documentation from XML documentation file. config.SetDocumentationProvider(new XmlDocumentationProvider(WebApiApplication.GetXmlCommentsPaths())); //// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type. //// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type //// formats by the available formatters. //config.SetSampleObjects(new Dictionary<Type, object> //{ // {typeof(string), "sample string"}, // {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}} //}); // Extend the following to provide factories for types not handled automatically (those lacking parameterless // constructors) or for which you prefer to use non-default property values. Line below provides a fallback // since automatic handling will fail and GeneratePageResult handles only a single type. #if Handle_PageResultOfT config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult); #endif // Extend the following to use a preset object directly as the sample for all actions that support a media // type, regardless of the body parameter or return type. The lines below avoid display of binary content. // The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object. config.SetSampleForMediaType( new TextSample("Binary JSON content. See http://bsonspec.org for details."), new MediaTypeHeaderValue("application/bson")); //// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format //// and have IEnumerable<string> as the body parameter or return type. //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>)); //// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values" //// and action named "Put". //config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put"); //// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png" //// on the controller named "Values" and action named "Get" with parameter "id". //config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id"); //// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>. //// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter. //config.SetActualRequestType(typeof(string), "Values", "Get"); //// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>. //// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string. //config.SetActualResponseType(typeof(string), "Values", "Post"); }
// GET api/Configuration?timestamp=03-Nov-2012%2012:00:00 public Microsoft.Research.Science.FetchClimate2.Serializable.FetchConfiguration Get(DateTime timestamp) { try { var configuration = WebApiApplication.GetFetchConfiguration(timestamp); var toSerizlize = new Microsoft.Research.Science.FetchClimate2.Serializable.FetchConfiguration(configuration); return(toSerizlize); } catch (ArgumentException exc) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest) { ReasonPhrase = exc.Message }); } }
public async Task <IHttpActionResult> AddTeacherAsync(TeacherVM teacher) { try { foreach (var item in dic_Sockets.Values) { if (item.deviceSerial == teacher.EquipmentNum) { //获取最大的学生ID,然后加一,就当作faceID了,再将这个faceID传入前端设备 int ID = TeacherManager.GetTeacherIdMax(); string faceID = (ID + 1).ToString(); string msgId = Guid.NewGuid().ToString();//定义一个标识,标识这个请求,设备回应的数据应该带上 var obj = new { msgId, faceID, faceName = teacher.Name, teacher.imageContent, url = "addFace" }; await item.socket.Send(JsonConvert.SerializeObject(obj)); JObject jObject = null; for (int i = 0; i < 5; i++) { Thread.Sleep(200); jObject = WebApiApplication.GetCache(msgId) as JObject; if (jObject != null) { if (jObject["errCode"].ToString() == "0") { await TeacherManager.AddTeacherAsync(Convert.ToInt32(faceID), teacher.Name, teacher.PhoneNum, teacher.SchoolID, teacher.EquipmentNum, "data:image/jpeg;base64," + teacher.imageContent); return(this.SendData(jObject)); } else { return(this.ErrorData(jObject["errMsg"].ToString())); } } else { continue; } } return(this.ErrorData("设备没有回应")); } } return(this.ErrorData("没有找到此设备,请查看设备序列号是否正确")); } catch (Exception ex) { LogTool.WriteError(ex.Message); return(this.ErrorData(ex.Message)); } }
public async Task <HttpResponseMessage> Post([FromBody] Activity activity, CancellationToken token) { if (activity != null) { switch (activity.GetActivityType()) { case ActivityTypes.Message: var container = WebApiApplication.FindContainer(); using (var scope = DialogModule.BeginLifetimeScope(container, activity)) { await Conversation.SendAsync(activity, () => scope.Resolve <IDialog <object> >(), token); } break; } } return(new HttpResponseMessage(HttpStatusCode.Accepted)); }