public override string DoInBackGround(string receivedData) { var srv = Server.GlobalInstance; LogController.WriteLog(new ServerLog($"Basic Server Module: Begin Request")); LogController.WriteLog(new ServerLog($"Received Data: {receivedData}")); IBasicServerController controller = (IBasicServerController)Activator.CreateInstance(srv.BasicServerControllerType, null); try { Stopwatch s = new Stopwatch(); s.Start(); ActionResult result = controller.RunAction(receivedData); s.Stop(); string resultToJson = JsonConvert.SerializeObject(result); byte[] resultBytes = srv.ServerEncoding.GetBytes(resultToJson); PreProcess.ClientSocket.Send(resultBytes); LogController.WriteLog(new ServerLog($"Request completed in ~{s.ElapsedMilliseconds}ms")); } catch (Exception ex) { PreProcess.ClientSocket.Send(srv.ServerEncoding.GetBytes($"Error: {ex.Message}")); LogController.WriteLog(new ServerLog($"Basic Server Module Error: {ex.Message}", ServerLogType.ERROR)); } PreProcess.Dispose(); return(string.Empty); }
private void WaitPendingRequestsCompletations() { while (Server.GlobalInstance.MaxThreadsCount > 0 && RequestProccess.ThreadCount >= Server.GlobalInstance.MaxThreadsCount) { LogController.WriteLog(new ServerLog("\nNumber of current threads has exceeded the set limit. Waiting for tasks to finish...", ServerLogType.ALERT)); Thread.Sleep(300); } }
private SocketRequest GetRequestSocket() { if (RequestBody == null) { return(null); } if (RequestBody != null) { if (RequestBody.Controller != null) { LogController.WriteLog(new ServerLog($"Processing request for action '{RequestBody.Controller}.{RequestBody.Action}'...", RequestBody.Controller, RequestBody.Action)); } } SocketRequest request = null; string controller = ""; string action = ""; try { string path = RequestBody.Action; controller = RequestBody.Controller; action = RequestBody.Action; request = new SocketRequest(); request.Client = socket; request.Action = action; request.Controller = GetController(controller); var parameters = typedObjManager.GetParameters(RequestBody.Parameters, action, request.Controller); parameters.ForEach(p => request.AddParameter(p)); if (!typedObjManager.ExistsAction(action, controller)) { throw new Exception($"Action '{action}' not exists in controller '{controller}'"); } return(request); } catch (Exception ex) { LogController.WriteLog(new ServerLog(ex.Message + "\n" + ex.StackTrace, controller, action, ServerLogType.ERROR)); request.HasErrors = true; request.InternalErrorMessage = ex.Message; return(request); } }
internal RequestProccess(string uriRequest, Socket clientSocket) { this.socket = clientSocket; try { RequestBody = JsonConvert.DeserializeObject <RequestBody>(uriRequest); this.socket = clientSocket; if (RequestBody == null) { return; } string log = $@" ******** BEGIN REQUEST ********* Controller: {RequestBody.Controller} Action: {RequestBody.Action} Parameters: "; if (RequestBody.Parameters != null) { RequestBody.Parameters.ForEach(p => { log += $"\n'{p.Name}'='{p.Value}'"; }); } log += @" ********************************"; LogController.WriteLog(new ServerLog(log, RequestBody.Controller, RequestBody.Action)); } catch (Exception ex) { string msg = ex.Message; if (ex.InnerException != null) { msg += ex.InnerException.Message; if (ex.InnerException.InnerException != null) { msg += ex.InnerException.InnerException.Message; } } new SocketRequest().ProcessResponse(ActionResult.Json("", ResponseStatus.ERROR, $@"A syntax error was detected while converting the request body to a server object. {msg}"), socket); } }
private void ProcessResponse(ActionResult response) { try { if (response.Type == 0) { SendJsonResponse(response); } if (response.Type == 1) { SendFileResponse(response); } } catch (Exception ex) { LogController.WriteLog(new ServerLog($"*** ERROR ON PROCESS RESPONSE:*** \n {ex.Message}", ServerLogType.ERROR)); ReleaseSession(); } }
internal ObjectRequestParameter GetObjectParameterType(string requestParameter, string actionName, string controllerName) { StreamReader stream = null; try { stream = new StreamReader( Directory.GetCurrentDirectory() + $@"\Mappings\{controllerName}.xml", Encoding.UTF8); XmlDocument xml = new XmlDocument(); xml.Load(stream); stream.Close(); stream.Dispose(); XmlNode node = FindNode(xml.ChildNodes, "ControllerMapping"); foreach (XmlNode requestMappingNode in node.ChildNodes) { if (requestMappingNode.Name.Equals("RequestMapping")) { foreach (XmlNode requestMappingParameter in requestMappingNode.ChildNodes) { if (requestParameter.StartsWith(requestMappingParameter.Attributes["alias"].Value)) { if (requestMappingParameter.ParentNode.Attributes["value"].Value == actionName) { return(new ObjectRequestParameter(requestMappingParameter.Attributes["alias"].Value, requestMappingParameter.Attributes["entity"].Value)); } } } } } return(null); } catch (Exception ex) { LogController.WriteLog(new ServerLog($"*** CHECK PARAMETER '{requestParameter}' FOR ACTION '{controllerName}.{actionName}' ERROR: *** \n{ex.Message}", controllerName, actionName, ServerLogType.ERROR)); return(null); } }
internal bool ExistsAction(string actionName, string controllerName) { LogController.WriteLog(new ServerLog($"Checking action '{controllerName}.{actionName}'...", controllerName, actionName)); StreamReader stream = null; try { stream = new StreamReader( Directory.GetCurrentDirectory() + $@"\Mappings\{controllerName}.xml", Encoding.UTF8); XmlDocument xml = new XmlDocument(); xml.Load(stream); stream.Close(); stream.Dispose(); XmlNode node = FindNode(xml.ChildNodes, "ControllerMapping"); foreach (XmlNode chNode in node.ChildNodes) { if (chNode.Name.Equals("RequestMapping")) { foreach (XmlAttribute a in chNode.Attributes) { if (a.Name.Equals("value") && a.Value.Equals(actionName)) { return(true); } } } } return(false); } catch (Exception ex) { LogController.WriteLog(new ServerLog($"*** CHECK ACTION '{controllerName}.{actionName}' ERROR: *** \n {ex.Message}", controllerName, actionName, ServerLogType.ERROR)); return(false); } }
private void AcceptCallback(IAsyncResult AR) { lock (lockAccept) { Socket socket; try { socket = ServerSocket.EndAccept(AR); var session = new SocketSession(socket, BufferSize); ClientSockets.Add(session); socket.BeginReceive(session.SessionStorage, 0, BufferSize, SocketFlags.None, ReceiveCallback, socket); ServerSocket.BeginAccept(AcceptCallback, null); } catch (Exception ex) // I cannot seem to avoid this (on exit when properly closing sockets) { LogController.WriteLog(new ServerLog("*** ERROR ***: \n" + ex.Message, ServerLogType.ERROR)); } } }
public void Start(bool waitForUserTypeExit = true) { if (Started) { throw new Exception("Server already has been started."); } Stopwatch sw = new Stopwatch(); sw.Start(); Initialize(); ServerSocket.Bind(new IPEndPoint(IPAddress.Any, Port)); ServerSocket.Listen(0); ServerSocket.BeginAccept(AcceptCallback, null); Started = true; ServerStarted?.Invoke(); RunServerStartupTasks(); sw.Stop(); LogController.WriteLog(new ServerLog($"Server started in {sw.ElapsedMilliseconds}ms", "Server", "Start")); LogController.WriteLog(new ServerLog($"Running at port {Port}")); Console.WriteLine("Type 'exit' to stop; 'reboot' to send reboot request event..."); string line = ""; if (waitForUserTypeExit) { while (line != "exit") { line = Console.ReadLine(); if (line == "reboot") { RebootRequest?.Invoke(); } } } }
private IController GetController(string controllerName) { try { LogController.WriteLog(new ServerLog($"Instantiating Controller {controllerName}...", controllerName, "")); var injectorMaker = Server.GlobalInstance.DependencyInjectorMakers.FirstOrDefault( maker => maker.ControllerName.Equals(controllerName) || maker.ControllerName.Equals("")); if (controllerName.Equals("ServerInfoController")) { injectorMaker = null; } ControllerRegister register = Server.GlobalInstance.RegisteredControllers.FirstOrDefault(c => c.Name.Equals(controllerName)); IController controller = (injectorMaker == null ? (IController)Activator.CreateInstance(register.Type) : (IController)Activator.CreateInstance(register.Type, injectorMaker.BuildInjectValues(RequestBody))); LogController.WriteLog(new ServerLog($"Instantiate Controller success! Controller name: {controller.GetType().FullName}", controllerName, "")); return(controller); } catch (Exception ex) { string msg = ex.Message; if (ex.InnerException != null) { msg += ex.InnerException.Message; } LogController.WriteLog(new ServerLog($@"Instantiate controller '{controllerName}' threw an exception. {msg}", controllerName, "", ServerLogType.ERROR)); throw new Exception($@"Instantiate controller '{controllerName}' threw an exception. {msg}"); } }
public override object DoInBackGround(int p) { SocketRequest request = null; try { request = GetRequestSocket(); if (request == null) { return(string.Empty); } if (request.HasErrors) { request.ProcessResponse(ActionResult.Json("", ResponseStatus.ERROR, request.InternalErrorMessage), socket); return(string.Empty); } controller = request.Controller; method = controller.GetType().GetMethod(request.Action); if (ActionLocker.ActionHasLock(controller, method.Name)) { request.ProcessResponse(ActionResult.Json("", ResponseStatus.LOCKED, $"This action is already being performed by another remote client and is currently blocked. Try again later"), socket); return(string.Empty); } foreach (ParameterInfo pi in method.GetParameters()) { if (pi.ParameterType == typeof(SocketRequest))//.Equals("MobileAppServer.ServerObjects.SocketRequest")) { request.AddParameter(new RequestParameter("request", request)); continue; } if (!request.Parameters.Any(rp => rp.Name.Equals(pi.Name))) { throw new Exception($"O parâmetro '{pi.Name}', necessário em {request.Controller.GetType().Name}/{request.Action}, não foi informado."); } } //GLOBAL Interceptors var globalInterceptors = Server.GlobalInstance.Interceptors.Where(i => i.ActionName.Equals("") && i.ControllerName.Equals("")).ToList(); if (!PreHandleInterceptors(globalInterceptors, new SocketRequest(request.Controller, request.Action, RequestBody.Parameters, socket))) { return(string.Empty); } //CONTROLLER (all actions) Interceptors var controllerInterceptors = Server.GlobalInstance.Interceptors.Where(i => i.ActionName.Equals("") && i.ControllerName.Equals(controller.GetType().Name)).ToList(); if (!PreHandleInterceptors(controllerInterceptors, new SocketRequest(request.Controller, request.Action, RequestBody.Parameters, socket))) { return(string.Empty); } //CONTROLLER (specific action) Interceptors var controllerActionInterceptors = Server.GlobalInstance.Interceptors.Where(i => i.ActionName.Equals(method.Name) && i.ControllerName.Equals(controller.GetType().Name)).ToList(); if (!PreHandleInterceptors(controllerActionInterceptors, new SocketRequest(request.Controller, request.Action, RequestBody.Parameters, socket))) { return(string.Empty); } object[] methodParameters = new object[request.Parameters.Count]; for (int i = 0; i < request.Parameters.Count; i++) { methodParameters[i] = request.Parameters[i].Value; } LogController.WriteLog(new ServerLog($"Invoking action '{controller.GetType().Name}.{method.Name}'...", controller.GetType().Name, method.Name)); Stopwatch w = new Stopwatch(); w.Start(); ActionResult result = (ActionResult)method.Invoke(controller, methodParameters); w.Stop(); if (w.ElapsedMilliseconds > 10000) { ServerAlertManager.CreateAlert(new ServerAlert(request.Controller.GetType().Name, request.Action, $"The action it is taking considerable time to execute ({w.ElapsedMilliseconds} ms). Review your code to improve performance.'")); } ActionLocker.ReleaseLock(controller, method.Name); LogController.WriteLog(new ServerLog($"Request completed in {w.ElapsedMilliseconds}ms", controller.GetType().Name, method.Name)); request.ProcessResponse(result, socket); return(result); } catch (Exception ex) { if (controller != null && method != null) { ActionLocker.ReleaseLock(controller, method.Name); } if (request != null) { request.ProcessResponse(ActionResult.Json("", ResponseStatus.ERROR, $"Process request error: \n{ ex.Message}"), socket); } return(string.Empty); } }
internal List <RequestParameter> GetParameters(List <RequestParameter> parameters, string action, IController controller) { LogController.WriteLog(new ServerLog($"Checking parameter list form action '{controller.GetType().Name}.{action}'...", controller.GetType().Name, action)); if (parameters == null) { return(new List <RequestParameter>()); } string currentObjRpAlias = string.Empty; Object entityParameterObject = this; List <RequestParameter> result = new List <RequestParameter>(); MethodInfo method = controller.GetType().GetMethod(action); foreach (RequestParameter parameter in parameters) { LogController.WriteLog(new ServerLog($"Setting parameter '{parameter.Name}' for action '{controller.GetType().Name}.{action}'...", controller.GetType().Name, action)); string pName = parameter.Name; string pValue = parameter.Value.ToString(); RequestParameter requestParameter = null; foreach (ParameterInfo pInfo in method.GetParameters()) { ObjectRequestParameter objectRequestParameter = GetObjectParameterType(pName, action, controller.GetType().Name); if (objectRequestParameter == null) { if (!pInfo.Name.Equals(pName)) { continue; } } // string objectParameterType = objRP.TypeName; if (objectRequestParameter != null) { if (objectRequestParameter.Alias != currentObjRpAlias || entityParameterObject.GetType().Name.Equals(this.GetType().Name)) { currentObjRpAlias = objectRequestParameter.Alias; ModelRegister model = Server.GlobalInstance.RegisteredModels.FirstOrDefault(m => m.ModeName == objectRequestParameter.TypeName); if (model == null) { LogController.WriteLog(new ServerLog($"Could not instantiate controller '{objectRequestParameter.TypeName}'. Check its mapping XML.", controller.GetType().Name, action, ServerLogType.ERROR)); throw new Exception($"Could not instantiate controller '{objectRequestParameter.TypeName}'. Check its mapping XML."); } Type type = model.ModelType; if (type == null) { LogController.WriteLog(new ServerLog($"Could not instantiate controller '{objectRequestParameter.TypeName}'. Check its mapping XML.", controller.GetType().Name, action, ServerLogType.ERROR)); throw new Exception($"Could not instantiate controller '{objectRequestParameter.TypeName}'. Check its mapping XML."); } entityParameterObject = Activator.CreateInstance(type); string parameterMethodName = pName.Substring(0, pName.IndexOf('.')); requestParameter = new RequestParameter(parameterMethodName, entityParameterObject); } int ptIndex = pName.IndexOf('.') + 1; string propertyName = pName.Substring(ptIndex, pName.Length - ptIndex); ConvertToType(entityParameterObject, propertyName, pValue); continue; } requestParameter = GetRequestParameterFromType(pInfo, pName, pValue); if (requestParameter != null) { break; } } if (requestParameter != null) { result.Add(requestParameter); } } return(result); }
private void Initialize() { GlobalInstance = this; Console.WriteLine("Socket App Server - version " + new ServerInfo().ServerVersion); ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); if (BufferSize == 0) { BufferSize = 4096 * 10; } if (ServerEncoding == null) { ServerEncoding = Encoding.Default; } if (MaxThreadsCount == 0) { MaxThreadsCount = 999999; } Requests = 0; if (Interceptors == null) { Interceptors = new List <IHandlerInterceptor>(); } if (DependencyInjectorMakers == null) { DependencyInjectorMakers = new List <IDependencyInjectorMaker>(); } if (Extensions == null) { Extensions = new List <IExtensibleFrameworkInterface>(); } RegisterController("ServerInfoController", typeof(ServerInfoController)); Console.WriteLine($"Server started with {BufferSize} bytes for buffer size \n"); Console.WriteLine($"Server Encoding: '{ServerEncoding.EncodingName}'"); if (MaxThreadsCount > 0) { Console.WriteLine($"Server max threads count: " + MaxThreadsCount); } foreach (IExtensibleFrameworkInterface extension in Extensions) { try { if (string.IsNullOrEmpty(extension.ExtensionName)) { throw new Exception($"Cannot be load unknown extension from assembly '{extension.GetType().Assembly.FullName}'"); } if (string.IsNullOrEmpty(extension.ExtensionVersion)) { throw new Exception($"Cannot be read extension version for '{extension.ExtensionName}'"); } if (string.IsNullOrEmpty(extension.ExtensionPublisher)) { throw new Exception($"Cannot be load unknown publisher extension for '{extension.ExtensionName}'"); } LogController.WriteLog($"Loading extension '{extension.ExtensionName}', version {extension.ExtensionVersion} by {extension.ExtensionPublisher}", ServerLogType.INFO); extension.Load(this); LogController.WriteLog($"Extension '{extension.ExtensionName}' successfully loaded"); } catch (Exception ex) { throw ex; } } }