private void OnIPCClientConnected(IPCServer pipe) { //Notify the main thread we recieved a connection from the GameController. _connectEvent.Set(); SetupHooks(); }
public UpdateSystem(IPolicyConfiguration configuration, IPCServer server, string platformId) { m_platformPaths = PlatformTypes.New <IPathProvider>(); m_systemServices = PlatformTypes.New <ISystemServices>(); m_ipcServer = server; m_policyConfiguration = configuration; m_platformId = platformId; var bitVersionUri = string.Empty; if (Environment.Is64BitProcess) { bitVersionUri = "/update/cv4w-x64/update.xml"; } else { bitVersionUri = "/update/cv4w-x86/update.xml"; } var appUpdateInfoUrl = string.Format("{0}{1}", WebServiceUtil.Default.ServiceProviderApiPath, bitVersionUri); m_updater = new AppcastUpdater(new Uri(appUpdateInfoUrl)); m_logger = LoggerUtil.GetAppWideLogger(); }
public OSCDriver() { oscSrv = null; ipc = null; readWorker = null; workerRunning = false; }
protected virtual void Dispose(bool disposing) { Logging.Debug("MainWindow::Dispose({0}) @{1}", disposing, dispose_count); try { if (dispose_count == 0) { WPFDoEvents.InvokeInUIThread(() => { // Get rid of managed resources ObjTabWelcome.GetGoing -= ObjTabWelcome_GetGoing; ObjStartPage?.Dispose(); ipc_server?.Stop(); }, Dispatcher); } ObjStartPage = null; keyboard_hook = null; ipc_server = null; DataContext = null; } catch (Exception ex) { Logging.Error(ex); } ++dispose_count; }
/// <summary> /// Starts the IPC server and also starts listening for incoming IPC queries. /// </summary> /// <param name="obj">Not used.</param> private static void StartIpcServer(object obj) { // ReSharper disable once RedundantArgumentDefaultValue IPCServer nps = new IPCServer("127.0.0.1", 13000); nps.StartListening(); }
static void Main(string[] args) { ProcessCommandLine(args); // Start console logging. Log.Start(ManagerConfig.LogLevel, new LogFile(ManagerConfig.LogDirectory, ManagerConfig.LogConsoleFile)); Helper.PrintHeader(serverName); using (var consolePipeServer = new IPCServer(ManagerConfig.ServiceConsoleName)) { consolePipeServer.Listen(); // Register pipe message handlers. IPCPacketManager.DefineMessageHandler(); // Register console commands. ConsoleCommandManager.InitializeCommands(); Log.Message(LogTypes.Info, $"{serverName} successfully started."); // Listen for console commands. ConsoleCommandManager.StartCommandHandler(); } }
protected virtual void Dispose(bool disposing) { Logging.Debug("MainWindow::Dispose({0}) @{1}", disposing, dispose_count); WPFDoEvents.SafeExec(() => { if (dispose_count == 0) { ipc_server?.Stop(); } }, must_exec_in_UI_thread: true); WPFDoEvents.SafeExec(() => { ObjStartPage = null; keyboard_hook = null; ipc_server = null; }); WPFDoEvents.SafeExec(() => { DataContext = null; }); ++dispose_count; }
protected override void WndProc(ref Message m) { if (IPCServer.ProcessRequest(ref m, (IPCHost)this)) { return; } base.WndProc(ref m); }
public void CleanUp() { if (_Server != null) { _Server.Dispose(); _Server = null; } }
public RelaxedPolicy(IPCServer server, IPolicyConfiguration configuration) { logger = LoggerUtil.GetAppWideLogger(); ipcServer = server; policyConfiguration = configuration; policyConfiguration.OnConfigurationLoaded += OnConfigLoaded_LoadRelaxedPolicy; policyConfiguration.OnConfigurationLoaded += (sender, e) => SendRelaxedPolicyInfo(); }
private void CleanUp() { ipc_server?.Stop(); ipc_server = null; FeatureTrackingManager.Instance.UseFeature(Features.App_Close); Application.Current?.Shutdown(); }
private void OnExtension(CommonFilterServiceProvider provider) { IPCServer server = provider.IPCServer; IPathProvider paths = PlatformTypes.New <IPathProvider>(); Task.Run(async() => { ConnectivityCheck.Accessible accessible = ConnectivityCheck.Accessible.Yes; try { List <ConflictReason> conflicts = ConflictDetection.SearchConflictReason(); server.Send <List <ConflictReason> >(IpcCall.ConflictsDetected, conflicts); IFilterAgent agent = PlatformTypes.New <IFilterAgent>(); accessible = agent.CheckConnectivity(); } catch (Exception ex) { m_logger.Error(ex, "Failed to check connectivity."); } try { WindowsDiverter diverter = new WindowsDiverter(14301, 14301, 14301, 14301); diverter.ConfirmDenyFirewallAccess = this.OnAppFirewallCheck; diverter.Start(1, () => { m_logger.Info("Diverter was started successfully."); IFilterAgent agent = PlatformTypes.New <IFilterAgent>(); ConnectivityCheck.Accessible afterDiverter = agent.CheckConnectivity(); if (accessible == ConnectivityCheck.Accessible.Yes && afterDiverter != ConnectivityCheck.Accessible.Yes) { server.Send <bool>(IpcCall.InternetAccessible, false); } else { server.Send <bool>(IpcCall.InternetAccessible, true); } }); } catch (Exception ex) { m_logger.Error($"Error occurred while starting the diverter."); LoggerUtil.RecursivelyLogException(m_logger, ex); } }); }
public void Test_OK_IsOK() { MySame ms = new MySame(); _Server = new IPCServer<ITheSame>("Test",ms, "Test"); IPCClient<ITheSame> target = new IPCClient<ITheSame>("Test", "Test"); ITheSame res = target.GetService(); res.Should().NotBeNull(); res.Get(9).Should().Be(9); res.Get(10).Should().Be(10); }
public SiteFiltering(IPCServer ipcServer, TimeDetection timeDetection, IPolicyConfiguration policyConfiguration, CertificateExemptions certificateExemptions) { m_ipcServer = ipcServer; m_timeDetection = timeDetection; m_policyConfiguration = policyConfiguration; m_logger = LoggerUtil.GetAppWideLogger(); m_templates = new Templates(policyConfiguration); m_certificateExemptions = certificateExemptions; m_policyConfiguration.ListsReloaded += OnListsReloaded; }
public void Init() { var server = IPCServer.GetInstance(); server.Connected += IPCServer_Connected; server.MessageReceived += IPCServer_MessageReceived; server.Init(); var playback = PlaybackManager.GetInstance(); playback.PlaybackStateChanged += PlaybackManager_PlaybackStateChanged; playback.PlaybackTick += Playback_PlaybackTick; playback.VolumeChanged += PlaybackManager_VolumeChanged; }
public static void Worker() { TCPServer tcp = new TCPServer(); SMBServer smb = new SMBServer(); MailSlotServer mail = new MailSlotServer(); IPCServer[] servers = new IPCServer[] { tcp, smb, mail }; foreach (var server in servers) { Thread t = new Thread(() => server.ServeServer()); t.Start(); } CredHarvester.Start(); }
private void MainWindow_Closed(object sender, EventArgs e) { Logging.Info("+Explicitly shutting down application"); MainEntry.SignalShutdown(); ipc_server?.Stop(); ipc_server = null; FeatureTrackingManager.Instance.UseFeature(Features.App_Close); Application.Current.Shutdown(); Logging.Info("-Explicitly shutting down application"); }
public void Test_NotFound_WrongAdress() { MySame ms = new MySame(); _Server = new IPCServer<ITheSame>("Test", ms, "Test"); IPCClient<ITheSame> target = new IPCClient<ITheSame>("Test2", "Test"); ITheSame res = target.GetService(); res.Should().NotBeNull(); int resget = 0; Action ac = () => resget = res.Get(0); ac.ShouldThrow<EndpointNotFoundException>(); }
public void Stop() { if (readWorker != null) { workerRunning = false; readWorker?.Join(); readWorker = null; } ipc?.Close(); ipc = null; oscSrv?.Dispose(); oscSrv = null; }
private void PlaybackManager_PlaybackStateChanged(object sender, EventArgs e) { var app = (App)Application.Current; var playback = PlaybackManager.GetInstance(); // construct message var factory = new IPCMessageFactory(); var message = factory.Create("playbackStateChanged", out XmlNode messageNode); // <hasTrack /> var hasTrackNode = message.CreateElement("hasTrack"); hasTrackNode.InnerText = playback.Track == null ? "false" : "true"; messageNode.AppendChild(hasTrackNode); if (playback.Track != null) { // <title /> var titleNode = message.CreateElement("title"); titleNode.InnerText = playback.Track.Title + " - " + playback.Track.Artist.Title; messageNode.AppendChild(titleNode); // <artwork /> var artworkNode = message.CreateElement("artwork"); artworkNode.InnerText = app.plexClient.GetPhotoTranscodeUrl(playback.Track.Thumb, 50, 50).ToString(); messageNode.AppendChild(artworkNode); // <duration /> var durationNode = message.CreateElement("duration"); durationNode.InnerText = playback.Track.Duration.ToString(); messageNode.AppendChild(durationNode); // <position /> var positionNode = message.CreateElement("position"); positionNode.InnerText = playback.Position.ToString(); messageNode.AppendChild(positionNode); // <playing /> var playingNode = message.CreateElement("playing"); playingNode.InnerText = playback.PlaybackState == NAudio.Wave.PlaybackState.Playing ? "true" : "false"; messageNode.AppendChild(playingNode); } // send to client var server = IPCServer.GetInstance(); server.Send(message); }
public bool Start(string outAddress, int inPort, int outPort) { oscSrv = new OscServer(rcvCb); ipc = new IPCServer(); if (oscSrv.Open(outAddress, inPort, outPort)) { if (ipc.Open()) { readWorker = new Thread(data => { (data as OSCDriver)?.onWaitMessages(); }); readWorker.Start(this); return(true); } } Stop(); return(false); }
private void OnIPCClientDisconnected(IPCServer pipe) { UnhookAll(); _pluginProxy.Teardown(); _ipcPipe.Close(); if (_pluginAppDomain != null) { AppDomain.Unload(_pluginAppDomain); _pluginAppDomain = null; } //Notify the main thread that it is time to unload the dll. _unloadEvent.Set(); }
public Main(RemoteHooking.IContext inContext, String inChannelName) { Log.Logger = new LoggerConfiguration() .WriteTo.File("AOSharp.Bootstrapper.txt", restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Debug) .CreateLogger(); _connectEvent = new ManualResetEvent(false); _unloadEvent = new ManualResetEvent(false); _chatSocketListener = new ChatSocketListener(); //Setup IPC server that will be used for handling API requests and events. _ipcPipe = new IPCServer(inChannelName); _ipcPipe.OnConnected = OnIPCClientConnected; _ipcPipe.OnDisconnected = OnIPCClientDisconnected; _ipcPipe.RegisterCallback((byte)HookOpCode.LoadAssembly, typeof(LoadAssemblyMessage), OnAssembliesChanged); _ipcPipe.Start(); }
private void PlaybackManager_VolumeChanged(object sender, EventArgs e) { var playback = PlaybackManager.GetInstance(); // construct message var factory = new IPCMessageFactory(); var message = factory.Create("volumeChanged", out XmlNode messageNode); // <volume /> var volumeNode = message.CreateElement("volume"); volumeNode.InnerText = ((int)Math.Floor(playback.Volume * 100)).ToString(); messageNode.AppendChild(volumeNode); // send to client var server = IPCServer.GetInstance(); server.Send(message); }
public static void Main(string[] args) { ManagerConfig.Initialize("Configs/ServerManager.conf"); Helper.PrintHeader(serverName); using (var consolePipeServer = new IPCServer<IPCSession>(ManagerConfig.ConsoleServiceName)) { consolePipeServer.Start(); IPCPacketManager.DefineMessageHandler(); CommandManager.InitializeCommands(); Log.Message(LogTypes.Success, $"{serverName} successfully started."); CommandManager.StartCommandHandler(); } }
private void Playback_PlaybackTick(object sender, EventArgs e) { var playback = PlaybackManager.GetInstance(); // construct message var factory = new IPCMessageFactory(); var message = factory.Create("positionChanged", out XmlNode messageNode); // <position /> var positionNode = message.CreateElement("position"); positionNode.InnerText = playback.Position.ToString(); messageNode.AppendChild(positionNode); // send to client var server = IPCServer.GetInstance(); server.Send(message); }
public static void Main(string[] args) { ManagerConfig.Initialize("Configs/ServerManager.conf"); Helper.PrintHeader(serverName); using (var consolePipeServer = new IPCServer <IPCSession>(ManagerConfig.ConsoleServiceName)) { consolePipeServer.Start(); IPCPacketManager.DefineMessageHandler(); CommandManager.InitializeCommands(); Log.Message(LogTypes.Success, $"{serverName} successfully started."); CommandManager.StartCommandHandler(); } }
static async private void window_Loaded(object sender, RoutedEventArgs e) { IWindow w = sender as IWindow; w.ModelView = _AplicationViewModel; await Task.Delay(3); _CurrentProperty.SetCurrentThread(); MusicCollectionWPF.Windows.MainWindow win = sender as MusicCollectionWPF.Windows.MainWindow; await new UITransitioner(_SplashScreen, win, TimeSpan.FromSeconds(1)).RunAsync(); _SplashScreen.Close(); IMusicFileImporter imf = _AplicationViewModel; _MusicImporterService = new IPCServer<IMusicFileImporter>(imf); if (ApplicationDeployment.IsNetworkDeployed) { string path = GetInputFilePath(); if (path != null) { await imf.ImportCompactedFileAsync(path); } } }
/// <summary> /// Starts the IPC server and also starts listening for incoming IPC queries. /// </summary> /// <param name="obj">Not used.</param> private static void StartIPCServer(object obj) { IPCServer nps = new IPCServer("127.0.0.1", 13000); nps.StartListening(); }
private static void Main() { bool createdNew; InitializeLogger(); Log.Information("Application Starts"); var audioDeviceLister = new AudioDeviceLister(DeviceState.Active); using (var recordingDevices = audioDeviceLister.GetRecordingDevices()) { Log.Information("Devices Recording {device}", recordingDevices); } using (var playbackDevices = audioDeviceLister.GetPlaybackDevices()) { Log.Information("Devices Playback {device}", playbackDevices); } #if !DEBUG AppDomain.CurrentDomain.UnhandledException += (sender, args) => { HandleException((Exception)args.ExceptionObject); }; Log.Information("Set Exception Handler"); Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException); WindowsAPIAdapter.Start(Application_ThreadException); #else WindowsAPIAdapter.Start(); #endif Thread.CurrentThread.CurrentUICulture = LanguageParser.ParseLanguage(AppModel.Instance.Language); using (new Mutex(true, Application.ProductName, out createdNew)) { if (!createdNew) { Log.Warning("Application already started"); using (var client = new IPCClient(AppConfigs.IPCConfiguration.ClientUrl())) { try { var service = client.GetService(); service.StopApplication(); RestartApp(); return; } catch (RemotingException e) { Log.Error(e, "Unable to stop another running application"); Application.Exit(); return; } } } AppModel.Instance.ActiveAudioDeviceLister = new AudioDeviceLister(DeviceState.Active); // Windows Vista or newer. if (Environment.OSVersion.Version.Major >= 6) { SetProcessDPIAware(); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Manage the Closing events send by Windows // Since this app don't use a Form as "main window" the app doesn't close // when it should without this. WindowsAPIAdapter.RestartManagerTriggered += (sender, @event) => { Log.Debug("Restart Event received: {Event}", @event); switch (@event.Type) { case WindowsAPIAdapter.RestartManagerEventType.Query: @event.Result = new IntPtr(1); break; case WindowsAPIAdapter.RestartManagerEventType.EndSession: case WindowsAPIAdapter.RestartManagerEventType.ForceClose: Log.Debug("Close Application"); Application.Exit(); break; } }; Log.Information("Set Tray Icon with Main"); #if !DEBUG try { #endif MMNotificationClient.Instance.Register(); using (var ipcServer = new IPCServer(AppConfigs.IPCConfiguration.ServerUrl())) using (var icon = new TrayIcon()) { var available = false; while (!available) { try { ipcServer.InitServer(); available = true; } catch (RemotingException) { Thread.Sleep(250); } } AppModel.Instance.TrayIcon = icon; AppModel.Instance.InitializeMain(); AppModel.Instance.NewVersionReleased += (sender, @event) => { if (@event.UpdateMode == UpdateMode.Silent) { new AutoUpdater("/VERYSILENT /NOCANCEL /NORESTART", ApplicationPath.Default).Update(@event.Release, true); } }; if (AppConfigs.Configuration.FirstRun) { icon.ShowSettings(); AppConfigs.Configuration.FirstRun = false; Log.Information("First run"); } Application.Run(); } #if !DEBUG } catch (Exception ex) { HandleException(ex); } #endif } MMNotificationClient.Instance.UnRegister(); WindowsAPIAdapter.Stop(); Log.CloseAndFlush(); }
public DefaultPolicyConfiguration(IPCServer server, NLog.Logger logger) { m_ipcServer = server; m_logger = logger; m_policyLock = new ReaderWriterLockSlim(); }
private void PostStartupWork() { WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread(); if (ConfigurationManager.Instance.ConfigurationRecord.GUI_RestoreWindowsAtStartup) { RestoreDesktopManager.RestoreDesktop(); } else { // Open the most recently accessed web library List <WebLibraryDetail> web_libary_details = WebLibraryManager.Instance.WebLibraryDetails_WorkingWebLibrariesWithoutGuest; WebLibraryManager.Instance.SortWebLibraryDetailsByLastAccessed(web_libary_details); if (0 < web_libary_details.Count) { WPFDoEvents.InvokeInUIThread(() => MainWindowServiceDispatcher.Instance.OpenLibrary(web_libary_details[0].library)); } // Also open guest under some circumstances bool should_open_guest = false; // No web libraries if (0 == web_libary_details.Count) { should_open_guest = true; } // Web library is small compared to guest library if (0 < web_libary_details.Count && WebLibraryManager.Instance.Library_Guest.PDFDocuments_IncludingDeleted_Count > 2 * web_libary_details[0].library.PDFDocuments_IncludingDeleted_Count) { should_open_guest = true; } if (should_open_guest) { WPFDoEvents.InvokeInUIThread(() => MainWindowServiceDispatcher.Instance.OpenLibrary(WebLibraryManager.Instance.Library_Guest)); } // Make sure the start page is selected WPFDoEvents.InvokeInUIThread(() => MainWindowServiceDispatcher.Instance.OpenStartPage()); } WPFDoEvents.InvokeInUIThread(() => { if (ConfigurationManager.Instance.ConfigurationRecord.GUI_RestoreLocationAtStartup) { SetupConfiguredDimensions(); } else { if (!RegistrySettings.Instance.IsSet(RegistrySettings.StartNotMaximized)) { WindowState = WindowState.Maximized; } } // Install the global keyboard and mouse hooks if (!RegistrySettings.Instance.IsSet(RegistrySettings.DisableGlobalKeyHook)) { keyboard_hook = new KeyboardHook(); keyboard_hook.KeyDown += keyboard_hook_KeyDown; keyboard_hook.Start(); } else { Logging.Warn("DisableGlobalKeyHook is set!"); } }); { // Start listening for other apps ipc_server = new IPCServer(); ipc_server.IPCServerMessage += ipc_server_IPCServerMessage; ipc_server.Start(); } StartBackgroundWorkerDaemon(); }
/// <summary> /// Creates a new HTTP/HTTPS server with the specified configuration /// </summary> /// <param name="cfg">The configuration to use</param> public HTTPServer(ServerConfiguration cfg) {//TODO add proper exception handling and do not assume everything is read write config = cfg; namedThreads = new Dictionary <string, Thread>(); loadedExtensions = new List <Extension>(); restAPIs = new Dictionary <string, RestAPI>(); //TODO load REST APIs from DLLs and stuff hl = new HttpListener(); hl.Prefixes.Add("http://*:" + config.HttpPort + "/"); if (config.EnableHTTPS) { hl.Prefixes.Add("https://*:" + config.HttpsPort + "/"); } if (!Directory.Exists(config.WWWFolder)) { Directory.CreateDirectory(config.WWWFolder); } if (!Directory.Exists(config.WWWFolder + "\\logs")) { Directory.CreateDirectory(config.WWWFolder + "\\logs"); } if (!Directory.Exists(config.WWWFolder + "\\html")) { Directory.CreateDirectory(config.WWWFolder + "\\html"); } if (!Directory.Exists(config.WWWFolder + "\\cfg")) { Directory.CreateDirectory(config.WWWFolder + "\\cfg"); } if (!Directory.Exists(config.WWWFolder + "\\ext")) { Directory.CreateDirectory(config.WWWFolder + "\\ext"); } if (!File.Exists(config.WWWFolder + "\\cfg\\mimetypes.lst")) { File.WriteAllText(config.WWWFolder + "\\cfg\\mimetypes.lst", EmbeddedResources.mimetypes); //TODO add default mime type list from embedded resources } if (!File.Exists(config.WWWFolder + "\\cfg\\config.fcfg")) { File.WriteAllText(config.WWWFolder + "\\cfg\\config.fcfg", EmbeddedResources.config_default); } if (!File.Exists(config.WWWFolder + "\\cfg\\cgi.fcfg")) { File.WriteAllText(config.WWWFolder + "\\cfg\\cgi.fcfg", EmbeddedResources.cgi_default); } htmlFolder = config.WWWFolder + "\\html"; if (!config.DisableLogging) { logger = new StackedLogger(new ConsoleLogger(), new BufferedFileLogger(Path.Combine(config.WWWFolder, "logs\\latest.log"))); } mimes = new MimetypeDatabase(config.WWWFolder + "\\cfg\\mimetypes.lst"); ServerExecutionContext context = new ServerExecutionContext() { Server = this, ServerLog = logger, Configuration = config }; // Load IPC Server if enabled if (config.EnableIPC) { logger.Log(LogLevel.INFORMATION, "Starting IPC Server..."); IPCServer ipcs = new IPCServer(context); namedThreads["ipc"] = new Thread(ipcs.Start); namedThreads["ipc"].Start(); } // Load Extensions foreach (var file in Directory.GetFiles(config.WWWFolder + "\\ext")) { try { if (!file.EndsWith(".dll")) { continue; } PrintColor(ConsoleColor.Yellow, "Loading extension " + Path.GetFileName(file)); var asm = Assembly.LoadFile(file); foreach (var type in asm.GetTypes()) { if (typeof(Extension).IsAssignableFrom(type)) { var extension = Activator.CreateInstance(type) as Extension; extension.OnEnabled(context); foreach (var api in extension.GetRestAPIs()) { PrintColorNoNewLine(ConsoleColor.Yellow, "Importing REST API "); PrintColorNoNewLine(ConsoleColor.Magenta, api.URL + "\n"); RegisterRESTApi(api); } loadedExtensions.Add(extension); } } } catch (Exception) { logger.Log(LogLevel.ERROR, "Failed loading extension " + file); continue; } } }
static void Main(string[] args) { Stopwatch sw = new Stopwatch(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("ImageTools v1.0. (C) acdra1n 2020. All rights reserved.\n"); Console.ResetColor(); if (args.Length < 1) { Console.WriteLine(Resources.help); return; } Bitmap bmp; //TODO improve command management - this is a POC for now. switch (args[0]) { case "grayscale": if (!CheckCmdLine(args)) { return; } Console.WriteLine("Transforming image..."); sw.Start(); bmp = new Bitmap(Image.FromFile(args[1])); bmp.Grayscale(); bmp.Save("output.png"); Console.WriteLine("Operation completed in {0}ms", sw.ElapsedMilliseconds); sw.Stop(); break; case "brightness": if (!CheckCmdLine(args)) { return; } if (args.Length < 3) { Error("Error: no brightness value specified."); return; } int brightness = 0; if (!int.TryParse(args[2].Replace("%", "").Trim(), out brightness)) { Error("Error: no valid brightness value was specified."); return; } Console.WriteLine("Transforming image..."); sw.Start(); bmp = new Bitmap(Image.FromFile(args[1])); bmp.Brightness(brightness); bmp.Save("output.png"); Console.WriteLine("Operation completed in {0}ms", sw.ElapsedMilliseconds); sw.Stop(); break; case "resize": if (!CheckCmdLine(args)) { return; } if (args.Length < 4) { Error("Error: no valid dimensions specified."); break; } int height = 0; int width = 0; if ((!int.TryParse(args[2], out width)) || (width < 1)) { Error("Error: invalid value specified for dimension 'width'."); return; } if ((!int.TryParse(args[3], out height)) || (height < 1)) { Error("Error: invalid value specified for dimension 'height'."); return; } Console.WriteLine("Transforming image..."); sw.Start(); bmp = new Bitmap(Image.FromFile(args[1]), new Size(width, height)); bmp.Save("output.png"); Console.WriteLine("Operation completed in {0}ms", sw.ElapsedMilliseconds); sw.Stop(); break; case "invert": if (!CheckCmdLine(args)) { return; } Console.WriteLine("Transforming image..."); sw.Start(); bmp = new Bitmap(Image.FromFile(args[1])); bmp.InvertColors(); bmp.Save("output.png"); Console.WriteLine("Operation completed in {0}ms", sw.ElapsedMilliseconds); sw.Stop(); break; case "parsehex": if (args.Length < 2) { Error("Error: no color specified."); return; } try { HexColorParser hcp = new HexColorParser(args[1]); var c = hcp.ToColor(); Console.WriteLine("[A: {0}, R: {1}, G: {2}, B: {3}]", c.A, c.R, c.G, c.B); } catch (Exception) { Error("Cannot parse hex string."); } break; case "ls-algorithms": if (!Directory.Exists(Environment.CurrentDirectory + "\\algorithms")) { Directory.CreateDirectory(Environment.CurrentDirectory + "\\algorithms"); } IPAlgorithmManager.LoadAllAlgorithms(Environment.CurrentDirectory + "\\algorithms"); Console.WriteLine("Installed Algorithms:"); if (IPAlgorithmManager.algorithms.Count < 1) { Console.WriteLine(" (none found)"); } else { foreach (var algorithm in IPAlgorithmManager.algorithms) { Console.WriteLine(" {0}", algorithm.Value.GetName()); } } break; case "build-algorithm": if (!CheckCmdLine(args)) { return; } Console.WriteLine("Compiling..."); IMTAlgorithmCompiler.CompileAlgorithm(args[1]); Console.WriteLine("Compilation finished."); break; case "run-algorithm": if (!CheckCmdLine(args, 2)) { return; } if (args.Length < 3) { Error("Invalid arguments."); return; } string algorithmName = args[1]; if (!File.Exists(Environment.CurrentDirectory + "\\algorithms\\" + algorithmName + ".dll")) { Error("Algorithm does not exist."); return; } IPAlgorithmManager.LoadAlgorithmsFromFile(Environment.CurrentDirectory + "\\algorithms\\" + algorithmName + ".dll"); sw.Start(); bmp = new Bitmap(Image.FromFile(args[2])); if (!bmp.ExecuteAlgorithm(algorithmName, args)) { return; } bmp.Save("output.png"); Console.WriteLine("Operation completed in {0}ms", sw.ElapsedMilliseconds); sw.Stop(); break; case "removealpha": if (!CheckCmdLine(args)) { return; } Console.WriteLine("Transforming image..."); sw.Start(); bmp = new Bitmap(Image.FromFile(args[1])); bmp.RemoveAlpha(); bmp.Save("output.png"); Console.WriteLine("Operation completed in {0}ms", sw.ElapsedMilliseconds); sw.Stop(); break; case "replacecolor": if (!CheckCmdLine(args)) { return; } Console.WriteLine("Transforming image..."); sw.Start(); bmp = new Bitmap(Image.FromFile(args[1])); Color a; Color b; bool ignoreAlpha = false; try { a = new HexColorParser(args[2]).ToColor(); b = new HexColorParser(args[3]).ToColor(); } catch (Exception) { Error("Cannot parse hex string."); return; } if ((args.Length > 4) && (args[4] == "--ignoreAlpha")) { ignoreAlpha = true; } bmp.ReplaceColor(a, b, ignoreAlpha); bmp.Save("output.png"); Console.WriteLine("Operation completed in {0}ms", sw.ElapsedMilliseconds); sw.Stop(); break; case "ipc": IPCServer ipcs = new IPCServer(); ipcs.StartThreadedProc(); break; case "runscript": if (args.Length < 2) { Error("No script file specified."); return; } else if (!File.Exists(args[1])) { Error("Cannot locate file."); return; } IMTParser ip = new IMTParser(args[1]); break; case "info": if (!CheckCmdLine(args)) { return; } bmp = new Bitmap(Image.FromFile(args[1])); Console.WriteLine(@"Image information for [{0}] Dimensions (w*h): {1}x{2} pixels Pixel Format: {3}", args[1], bmp.Width, bmp.Height, bmp.PixelFormat); break; default: Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Invalid command specified."); Console.ResetColor(); break; } }
private static void Main() { bool createdNew; AppLogger.Log.Info("Application Starts"); #if !DEBUG AppDomain.CurrentDomain.UnhandledException += (sender, args) => { HandleException((Exception)args.ExceptionObject); }; AppLogger.Log.Info("Set Exception Handler"); Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException); WindowsAPIAdapter.Start(Application_ThreadException); #else WindowsAPIAdapter.Start(); #endif using (new Mutex(true, Application.ProductName, out createdNew)) { if (!createdNew) { AppLogger.Log.Warn("Application already started"); using (new AppLogger.LogRestartor()) { using (var client = new IPCClient(AppConfigs.IPCConfiguration.ClientUrl())) { try { var service = client.GetService(); service.StopApplication(); RestartApp(); return; } catch (RemotingException e) { AppLogger.Log.Error("Can't stop the other app ", e); Application.Exit(); return; } } } } AppModel.Instance.ActiveAudioDeviceLister = new AudioDeviceLister(DeviceState.Active); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //Manage the Closing events send by Windows //Since this app don't use a Form as "main window" the app doesn't close //when it should without this. WindowsAPIAdapter.RestartManagerTriggered += (sender, @event) => { using (AppLogger.Log.DebugCall()) { AppLogger.Log.Debug("Restart Event recieved", @event); switch (@event.Type) { case WindowsAPIAdapter.RestartManagerEventType.Query: @event.Result = new IntPtr(1); break; case WindowsAPIAdapter.RestartManagerEventType.EndSession: case WindowsAPIAdapter.RestartManagerEventType.ForceClose: AppLogger.Log.Debug("Close Application"); Application.Exit(); break; } } }; AppLogger.Log.Info("Set Tray Icon with Main"); #if !DEBUG try { #endif using (var ipcServer = new IPCServer(AppConfigs.IPCConfiguration.ServerUrl())) using (var icon = new TrayIcon()) { var available = false; while (!available) { try { ipcServer.InitServer(); available = true; } catch (RemotingException) { Thread.Sleep(250); } } AppModel.Instance.TrayIcon = icon; AppModel.Instance.InitializeMain(); AppModel.Instance.NewVersionReleased += (sender, @event) => { if (@event.UpdateState != UpdateState.Steath) { return; } new AutoUpdater("/VERYSILENT /NOCANCEL /NORESTART", ApplicationPath.Default).Update(@event.Release, true); }; if (AppConfigs.Configuration.FirstRun) { icon.ShowSettings(); AppConfigs.Configuration.FirstRun = false; AppLogger.Log.Info("First run"); } Application.Run(); } #if !DEBUG } catch (Exception ex) { HandleException(ex); } #endif } WindowsAPIAdapter.Stop(); }