/// <summary> /// Starts up a timer to check if there are any forms open. /// If there are no forms open, closes the application /// </summary> static void StartFormTimer() { //Setting up the timer new Thread(new ThreadStart(() => { while (true) { try { FormCollection fc = Application.OpenForms; if (fc.Count == 1) { ILogger.AddToLog("Info", "Detected no open forms! Closing application."); ClosingEvents(); break; } Thread.Sleep(50); } catch { ClosingEvents(); break; } } })).Start(); }
public static void InitializeServerConnections() { string ServerIp = "indiegoat.us"; string ExternalIP = ManagedResources.GetExternalIP(); string IndieGoatIP = ManagedResources.GetIndiegoatIP(); Console.WriteLine(ExternalIP); Console.WriteLine(IndieGoatIP); ILogger.AddToLog("INFO", "Found both External and Indie Goat IP. External : " + ExternalIP + ", IndieGoat : " + IndieGoatIP + "."); if (ExternalIP.Contains(IndieGoatIP)) { ServerIp = "192.168.0.16"; ILogger.AddToLog("WARN", "Changed to a IndieGoat localized IP! This may accure if you are connected locally to the IndieGoat Universal Server. Network issues may be apparent."); } ILogger.AddToLog("INFO", ServerIp); ManagedResources.Updater = new UniversalServiceUpdater(); ILogger.AddToLog("INFO", "Initialized Service Updater, entering update loop"); while (true) { if (ManagedResources.Updater.CheckUniversalAPI()) { break; } } ILogger.AddToLog("INFO", "Finished checking UniversalAPI install"); ManagedResources.Updater.CheckUpdate(ServerIp, 7878); ILogger.AddToLog("INFO", "Finished checking for update."); ILogger.AddToLog("INFO", "Done initializing network connections."); }
public void SetID(string UserID, string UserEndpoint) { userID = UserID; userEndpoint = UserEndpoint; UserDirectory = UserDirectories + @"\" + userID; if (!Directory.Exists(UserDirectory)) { Directory.CreateDirectory(UserDirectory); } ClientStorage.ShowLog = false; ClientStorage.SettingsFileName = "UserData.dat"; ClientStorage.SettingsDirectory = UserDirectory; this.IsLoggedIn = true; if (ClientStorage.CheckSetting(_UserLoginDates)) { List <string> oldData = ClientStorage.ReadSetting(_UserLoginDates).Split(Seperators, StringSplitOptions.RemoveEmptyEntries).ToList(); oldData.Add(DateTime.Now.ToString() + internalSeperator + userEndpoint); string newData = String.Join(Seperators[0], oldData); ClientStorage.EditSetting(_UserLoginDates, newData); } else { string newData = DateTime.Now.ToString() + internalSeperator + userEndpoint; ClientStorage.EditSetting(_UserLoginDates, newData); } ILogger.AddToLog("INFO", "Client [" + userEndpoint + "] has logged in with ID [" + userID + "]"); }
public static void InitializeCefSharp() { //Initialize CefSharp Cef.Initialize(GetCefSettings()); ILogger.AddToLog("CEFSHARP", "Initialization Completed!"); }
private void CreateServer(string ServerName) { string oldSettingValue = settingsFramework.ReadSetting(_servers); if (oldSettingValue != null) { List <string> _Servers = oldSettingValue.Split(new string[] { seperator }, StringSplitOptions.RemoveEmptyEntries).ToList(); foreach (string s in _Servers) { if (s.ToUpper() == ServerName.ToUpper()) { ILogger.AddToLog("WARN", "Server already exist!"); return; } } _Servers.Add(ServerName); string newSettingValue = string.Join(seperator, _Servers); settingsFramework.EditSetting(_servers, newSettingValue); } else { string newSettingValue = ServerName + seperator; settingsFramework.EditSetting(_servers, newSettingValue); } UniversalServerObject newServer = new UniversalServerObject(ServerName, Environment.CurrentDirectory); servers.Add(newServer); ILogger.AddToLog("INFO", "Created " + ServerName + " sucessfully! Please start the server."); }
public ShoppingCartMiddleware(RequestDelegate next, IShoppingCartService shoppingCartService, ISettingsProvider settingsProvider, ILogger logger, IPluginHelperService pluginHelperService) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } if (settingsProvider == null) { throw new ArgumentNullException(nameof(settingsProvider)); } _next = next; _shoppingCartService = shoppingCartService ?? throw new ArgumentNullException(nameof(shoppingCartService)); if (pluginHelperService == null || !pluginHelperService.PluginLoaded(Constants.PluginNameUserSession, out int version)) { logger.AddToLog(LogLevel.Error, new Exception(Constants.UserSessionServiceNotFound), nameof(ShoppingCartMiddleware)); } _cartSettings = settingsProvider.GetSettings <CartSettings>(Constants.ShoppingCart); }
private string ReadClient(ClientContext context, IAsyncResult ar) { string Content = String.Empty; context.Stream.Flush(); context.sb = new StringBuilder(); try { if (context == null) { return(null); } Socket handler = context.Client.Client; int read = handler.EndReceive(ar); // Data was read from the client socket. if (read > 0) { string b = context.sb.Append(Encoding.UTF8.GetString(context.Buffer, 0, read)).ToString(); string[] Result = b.Split(new string[] { "<EOF>" }, StringSplitOptions.RemoveEmptyEntries); return(Result[0]); } return(null); } catch (Exception e) { ILogger.LogExceptions(e); ILogger.AddToLog("INFO", "Disconnect client from ReadClient"); DisconnectClient(context); return(null); } }
public void SaveLogFile(string ApplicationName, string Log) { try { //Get's the application log directory string AD = Path.Combine(UserLogDirectory, ApplicationName); int fileCount = Directory.GetFiles(AD).Length; string NewApplicationLogFile = Path.Combine(AD, "Log " + fileCount + ".log"); //Delete's the log file if it exist's if (File.Exists(NewApplicationLogFile)) { ILogger.AddToLog("WARN", "Application log already exist's! Deleting the current one."); File.Delete(NewApplicationLogFile); } //Creates a new log file File.Create(NewApplicationLogFile).Close(); //Writes log file content File.WriteAllText(NewApplicationLogFile, Log); } catch (Exception e) { ILogger.AddToLog("ClientTracker", "Error while ClientTracker was trying to log a setting! " + e.Message); ILogger.AddToLog("ClientTracker", e.StackTrace); } }
public IActionResult Index() { IndexViewModel model = new IndexViewModel(GetModelData(), _documentationService.GetCustomData("Header", Languages.LanguageStrings.APIReference), _documentationService.GetCustomData("Description", Languages.LanguageStrings.InThisDocument)); List <Document> documents = _documentationService.GetDocuments() .Where(d => d.DocumentType == DocumentType.Assembly || d.DocumentType == DocumentType.Custom) .OrderBy(o => o.SortOrder).ThenBy(o => o.Title) .ToList(); foreach (Document doc in documents) { if (!model.AssemblyNames.ContainsKey(doc.Title)) { if (String.IsNullOrEmpty(doc.ShortDescription)) { _logger.AddToLog(LogLevel.Information, $"No short description for document {doc.Title}"); } model.AssemblyNames.Add(doc.Title, new DocumentationModule(doc.Title, doc.ShortDescription)); } } return(View(model)); }
public void ConsolePluginInvoke(string[] args) { bool found = false; if (pluginsLoaded) { foreach (UniversalPlugin plugin in serverPlugins) { if (args[0].ToUpper() == plugin.core.Name.ToUpper()) { found = true; try { plugin.core.ConsoleInvoke(args, serverPluginLogger); } catch (Exception e) { ILogger.AddToLog("WARN", "Exception occured while executing a Console Plugin Command!"); ILogger.LogExceptions(e); } break; } } } else { ILogger.AddToLog("INFO", "Plugins hasn't been loaded in the appdomain yet! Please load them by starting the server."); } if (!found) { ILogger.AddToLog("INFO", "Couldn't find plugin [" + args[0] + "] please make sure that plugin is installed and loaded! "); } }
public void LogSetting(string SettingName, string SettingValue) { try { string settingDirectoryValue = SettingDirectory + @"\" + SettingName + ".dat"; string logEvent = DateTime.Now.ToString() + Seperator + ClientIP + Seperator + SettingValue; if (File.Exists(settingDirectoryValue)) { List <string> values = File.ReadAllLines(settingDirectoryValue).ToList(); values.Add(logEvent); File.WriteAllLines(settingDirectoryValue, values); } else { File.Create(settingDirectoryValue).Close();; File.WriteAllText(settingDirectoryValue, logEvent); } } catch (Exception e) { ILogger.AddToLog("ClientTracker", "Error while ClientTracker was trying to log a setting! " + e.Message); ILogger.AddToLog("ClientTracker", e.StackTrace); } }
public void LogIP(string IP) { try { ClientIP = IP; if (File.Exists(LogIPDirectory)) { List <string> IPs = File.ReadAllLines(LogIPDirectory).ToList(); bool addToList = true; foreach (string s in IPs) { if (s == IP) { addToList = false; } } if (addToList) { IPs.Add(IP); } File.WriteAllLines(LogIPDirectory, IPs); } else { File.Create(LogIPDirectory).Close(); File.WriteAllText(LogIPDirectory, IP); } } catch (Exception e) { ILogger.AddToLog("ClientTracker", "Error while ClientTracker was trying to log a new ip! " + e.Message); ILogger.AddToLog("ClientTracker", e.StackTrace); } }
static void Main(string[] args) { ILogger.SetLoggingEvents(); //Set local param ApplicationSearchName = args[0]; ApplicationDirectory = args[1]; DownloadURI = args[2]; ILogger.AddToLog("info", "Application Name : " + ApplicationSearchName); ILogger.AddToLog("info", "Application Directory : " + ApplicationDirectory); ILogger.AddToLog("info", "DownloadURI : " + DownloadURI); //Get process updateProgram = Process.GetProcessesByName(ApplicationSearchName).FirstOrDefault(); ILogger.AddToLog("info", "Got process! Verifying"); if (updateProgram == null) { ILogger.AddToLog("error", "Process is null!"); } if (File.Exists(Application.StartupPath + "\\" + ApplicationSearchName + ".zip")) { File.Delete(Application.StartupPath + "\\" + ApplicationSearchName + ".zip"); } DownloadUpdate(); UpdateLoop(); }
/// <summary> /// Extracts the update and then closes /// </summary> private static void ExtractUpdate() { while (true) { try { ILogger.AddToLog("info", "Deleting the directory and remaking it"); //Deletes all files in a directory DirectoryInfo di = new DirectoryInfo(ApplicationDirectory); foreach (FileInfo file in di.GetFiles()) { file.Delete(); } foreach (DirectoryInfo dir in di.GetDirectories()) { dir.Delete(true); } break; } catch { } } ILogger.AddToLog("info", "Extracting update!"); //Extracts all files into the application directory using (ZipFile zip = ZipFile.Read(Application.StartupPath + "\\" + ApplicationSearchName + ".zip")) { zip.ExtractAll(ApplicationDirectory); } ILogger.AddToLog("info", "Extract update!"); Environment.Exit(1); }
private void DeleteServer(string ServerName) { foreach (UniversalServerObject USO in servers) { if (USO.ServerName == ServerName) { servers.Remove(USO); USO.Dispose(); break; } } string Dir = Environment.CurrentDirectory + @"\" + ServerName; if (Directory.Exists(Dir)) { Directory.Delete(Dir, true); } string oldSettingValue = settingsFramework.ReadSetting(_servers); if (oldSettingValue != null) { List <string> _Servers = oldSettingValue.Split(new string[] { seperator }, StringSplitOptions.RemoveEmptyEntries).ToList(); _Servers.Remove(ServerName); string newSettingValue = string.Join(seperator, _Servers); settingsFramework.EditSetting(_servers, newSettingValue); } ILogger.AddToLog("INFO", "Deleted " + ServerName + " sucessfully!"); }
public void RunCommand(string[] args) { var downloadUrl = new Uri(args[1]); var server = args[2]; try { using (var webClient = new WebClient()) { string fileName = Path.GetFileName(downloadUrl.LocalPath); ILogger.AddToLog(ILogger.Levels.INFO, $"Downloading plugin {fileName} for server {server}"); webClient.DownloadProgressChanged += (obj, arg) => { var translatedArgs = (DownloadProgressChangedEventArgs)arg; Console.Write("\r --> Downloading " + fileName + ": " + string.Format("{0:n0}", translatedArgs.BytesReceived / 1000) + " kb"); }; webClient.DownloadFileCompleted += (obj, arg) => { ILogger.AddToLog(ILogger.Levels.INFO, $"Downloading plugin {fileName} completed! Please restart the server."); }; var universalServer = Universalserver.TcpServers.FirstOrDefault(x => Utility.EqualsIgnoreCase(x.ServerName, server)); var downloadDirectory = universalServer.GetPluginDirectory; webClient.DownloadFileAsync(downloadUrl, Path.Combine(downloadDirectory, fileName)); } } catch (Exception e) { ILogger.LogExceptions(e); } }
/// <summary> /// Tries to update the program /// </summary> private static void UpdateLoop() { Thread CheckApplicationThread = new Thread(new ThreadStart(() => { ILogger.AddToLog("info", "Running loop"); while (true) { Console.WriteLine("In Loop"); //Check if the program has exit. if (updateProgram.HasExited) { //Verifying that all instances of this application has exited. updateProgram = Process.GetProcessesByName(ApplicationSearchName).FirstOrDefault(); if (updateProgram == null) { ILogger.AddToLog("info", "Application exit!"); //Extracts the update ExtractUpdate(); } } Thread.Sleep(5000); } })); CheckApplicationThread.Start(); }
public RestrictIpMiddleware(RequestDelegate next, IActionDescriptorCollectionProvider routeProvider, IRouteDataService routeDataService, IPluginHelperService pluginHelperService, IPluginTypesService pluginTypesService, ISettingsProvider settingsProvider, ILogger logger) { if (routeProvider == null) { throw new ArgumentNullException(nameof(routeProvider)); } if (routeDataService == null) { throw new ArgumentNullException(nameof(routeDataService)); } if (pluginHelperService == null) { throw new ArgumentNullException(nameof(pluginHelperService)); } _next = next; _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _localIpAddresses = new HashSet <string>(); _restrictedRoutes = new Dictionary <string, List <string> >(); GetLocalIpAddresses(_localIpAddresses); RestrictIpSettings settings = settingsProvider.GetSettings <RestrictIpSettings>("RestrictedIpRoutes.Plugin"); _disabled = settings.Disabled; if (_disabled) { _logger.AddToLog(LogLevel.Information, RestrictedIpDisabled); } LoadRestrictedIpRouteData(routeProvider, routeDataService, pluginTypesService, settings); }
public async Task Invoke(HttpContext context) { bool passRequestOn = true; try { if (_disabled) { return; } using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings)) { string route = RouteLowered(context); string userIpAddress = GetIpAddress(context); bool isLocalAddress = _localIpAddresses.Contains(userIpAddress); #if !DEBUG // always allow local connections if (isLocalAddress) { return; } #endif foreach (KeyValuePair <string, List <string> > restrictedRoute in _restrictedRoutes) { if (route.StartsWith(restrictedRoute.Key)) { foreach (string restrictedIp in restrictedRoute.Value) { if ((isLocalAddress && restrictedIp == LocalHost) || (String.IsNullOrEmpty(restrictedIp))) { return; } if (userIpAddress.StartsWith(restrictedIp)) { return; } } // if we get here, we are in a restricted route and ip does not match, so fail with forbidden passRequestOn = false; context.Response.StatusCode = 403; _logger.AddToLog(LogLevel.IpRestricted, String.Format(RouteForbidden, userIpAddress, route)); } } } } finally { if (passRequestOn) { await _next(context); } } }
private static void EditCefCommandLine(string key, string Value) { //Add to command line cfSettings.CefCommandLineArgs.Add(key, Value); //logging ILogger.AddToLog("CefSharp", "Added : " + key + " with a value of : " + Value); }
private void GenerateBrowserHandle() { SettingsManager.BrowserEngine = SettingsManager.BrowserEngines.CefSharp; if (SettingsManager.BrowserEngine == SettingsManager.BrowserEngines.CefSharp) { browser = new CefSharpHandle(); ILogger.AddToLog("IBrowser", "Using CEFSHARP as browser engine."); } }
/// <summary> /// Used to format and add a value to the history /// </summary> /// <param name="URL">The link for the website</param> /// <param name="date">Date when the website was viewed</param> /// <param name="Title">Title of the website</param> public static void AddToHistory(string URL, string date, string Title) { //Format the Value string value = URL + seperator + Title + seperator + date; //Insert the History value at index 0 History.Insert(0, value); ILogger.AddToLog("IHistory", "Added a new history entry! : " + value); }
private void commandLine() { ILogger.AddToLog("INFO", "Type Help for a list of commands.."); while (true) { Console.Write(">"); string Command = Console.ReadLine(); string[] CommandArgs = Command.Split(' '); if (CommandArgs[0].ToUpper() == "CREATESERVER" || CommandArgs[0].ToUpper() == "CREATE") { CreateServer(CommandArgs[1]); } if (CommandArgs[0].ToUpper() == "DELETESERVER" || CommandArgs[0].ToUpper() == "DELETE") { DeleteServer(CommandArgs[1]); } if (CommandArgs[0].ToUpper() == "LIST" || CommandArgs[0].ToUpper() == "LISTSERVER" || CommandArgs[0].ToUpper() == "LISTSERVERS") { List(); } if (CommandArgs[0].ToUpper() == "EDITSERVERSETTING") { EditServerSetting(CommandArgs[1], CommandArgs[2], CommandArgs[3]); } if (CommandArgs[0].ToUpper() == "HELP") { try { Help(int.Parse(CommandArgs[1])); } catch { Help(); } } if (CommandArgs[0].ToUpper() == "STARTSERVER" || CommandArgs[0].ToUpper() == "START") { StartServer(CommandArgs[1]); } if (CommandArgs[0].ToUpper() == "EXIT" || CommandArgs[0].ToUpper() == "CLOSE") { try { if (CommandArgs[1] == null) { Exit(); } else { Exit(CommandArgs[1]); } } catch { Exit(); } } } }
public void AgregarLog <T>(T log) { ILogger logger = null; if (this.loggers.TryGetValue(typeof(T).FullName, out logger)) { logger.AddToLog(log); } }
public List <UniversalPlugin> LoadPlugins(string PluginDirectory) { returnPlugins = new List <UniversalPlugin>(); string pluginDataDirectory = Path.Combine(PluginDirectory, "Data"); ILogger.AddWhitespace(); if (!Directory.Exists(pluginDataDirectory)) { Directory.CreateDirectory(pluginDataDirectory); } if (Directory.Exists(PluginDirectory)) { string[] files = Directory.GetFiles(PluginDirectory); foreach (string file in files) { if (file.EndsWith(".dll")) { Assembly.LoadFile(Path.GetFullPath(file)); } } } else { Directory.CreateDirectory(PluginDirectory); } Type interfaceType = typeof(IUniversalPlugin); Type[] types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).Where(p => interfaceType.IsAssignableFrom(p) && p.IsClass).ToArray(); foreach (Type type in types) { try { IUniversalPlugin plugin = (IUniversalPlugin)Activator.CreateInstance(type); UniversalPlugin pluginInstance = new UniversalPlugin(plugin); pluginInstance.core = plugin; ILogger.AddToLog(ILogger.Levels.INFO, "Initializing [" + pluginInstance.core.Name + "]"); pluginInstance.core.SetUniversalPluginAPI(pluginInstance); pluginInstance.core.Initialize(Path.Combine(pluginDataDirectory, pluginInstance.core.Name), pluginInstance); returnPlugins.Add(pluginInstance); ILogger.AddToLog(ILogger.Levels.INFO, "Plugin [" + pluginInstance.core.Name + "] Fully loaded!"); } catch (Exception e) { //Tried to load the assembly instance } } ILogger.AddWhitespace(); return(returnPlugins); }
/// <summary> /// Sets the events of application exceptions. /// </summary> static void SetApplicationExceptions() { //App doamin and application events for logging. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Application.ApplicationExit += Application_ApplicationExit; AppDomain.CurrentDomain.ProcessExit += Application_ApplicationExit; Application.ThreadException += Application_ThreadException; ILogger.AddToLog("INFO", "Set handle's for all application exceptions's"); }
/// <summary> /// Initializes stripe API /// </summary> static void InitializeStripe() { //Instalization for Stripe Stripe.StripeConfiguration.SetApiKey("sk_live_gTIkgQoj5jZGrpGJ7vj3x4Mt"); ILogger.AddToLog("Stripe", "Instalization complete!"); //**Stripe is currently not being used in this application. This thead is meant for testing. And as soon as we figure //Out how to store the API key. We will not be using STRIPE to accept donations. Except we are moving from STRIPE to //Patreon. As feedback from our open reddit AMA. We do agree, keeping a private API key public is not secure. }
private void Help(int Page = 0) { ILogger.AddWhitespace(); ILogger.AddToLog("INFO", "CreateServer, Create [ServerName] - Creates a new server, that you'll be able to manage"); ILogger.AddToLog("INFO", "DeleteServer, Delete [ServerName] - Deletes a current server, and related files."); ILogger.AddToLog("INFO", "List, ListServer, ListServers - List all currently created servers"); ILogger.AddToLog("INFO", "EditServerSetting - Use the servers settings framework to write a server setting."); ILogger.AddToLog("INFO", "Exit, Close [ServerName] - If ServerName is null, closes the application. Else closes the server."); ILogger.AddWhitespace(); }
private void StartServer(string ServerName) { UniversalServerObject serverObject = GetServerObject(ServerName); if (serverObject == null) { ILogger.AddToLog("INFO", "Server doesn't exist!"); return; } serverObject.StartListener(); ILogger.AddToLog("INFO", ServerName + " is now listening for connections!"); }
private void onSocketAccepted(IAsyncResult result) { // This is the client socket, where you send/receive data from after accepting. Keep it in a List<Socket> collection if you need to. Socket client = serverlistener.EndAccept(result); ILogger.AddToLog("INFO", "Accepted client endpoint [" + client.RemoteEndPoint + "]"); ClientWorkObject workObject = new ClientWorkObject(client, this); client.BeginReceive(workObject.buffer, 0, workObject.buffer.Length, SocketFlags.None, onDataReceived, workObject); serverlistener.BeginAccept(onSocketAccepted, null); }