static void Main(string[] args) { bool result; var mutex = new System.Threading.Mutex(true, "MusicSorter", out result); if (!result) { if (args.Length > 0) { try { //timeout set to 3 seconds NamedPipeListener <String> .SendMessage(args[0]); //load new song in first instance instead } catch (Exception ex) { MessageBox.Show(ex.Message); } } return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm(args)); GC.KeepAlive(mutex); //do not release the mutex }
public void Initialize(IPlugin plugin) { pipeListener = new NamedPipeListener<string>("SlavApp.Minion.Resembler"); pipeListener.MessageReceived += (sender, e) => { OnMessageReceived(plugin, e); }; pipeListener.Error += (sender, e) => { OnError(e); }; pipeListener.Start(); }
private async Task TestBodyStream_Impl() { var listener = new NamedPipeListener(TestContext.TestName); var payload = Encoding.UTF8.GetBytes("Hello world"); await listener.StartAsync(con => { Task.Run(async() => { try { await con.WriteAsync(payload, 0, payload.Length); } catch (Exception e) { Debug.WriteLine("... WriteAsync exception:" + e.Message); } }); }, CancellationToken.None); var dialer = new NamedPipeDialer(TestContext.TestName); var stream = await dialer.DialAsync(new HttpRequestMessage(), CancellationToken.None); var bodyStream = new BodyStream(stream, payload.Length); var data = new byte[4096]; var read = await bodyStream.ReadAsync(data, 0, data.Length); Assert.AreEqual(payload.Length, read); read = await bodyStream.ReadAsync(data, 0, data.Length); Assert.AreEqual(0, read); // Clean up await listener.StopAsync(CancellationToken.None); }
public static void Main() { Console.WriteLine("NamedPipe IPC engine"); var ipcListener = new NamedPipeListener(NamedPipeConstants.PipeName); var ipcEngine = new ServiceIpcEngine(ipcListener); ipcEngine.PingCmdReceived += OnPingCmdReceived; ipcEngine.ActionCmdReceived += OnActionCmdReceived; ipcEngine.FuncCmdReceived += OnFuncCmdReceived; ipcEngine.Initialize(); ipcEngine.Start(); Console.WriteLine("Press <ENTER> to exit..."); Console.ReadLine(); ipcEngine.Stop(); ipcEngine.Dispose(); }
private void MainForm_Load(object sender, EventArgs e) { try { Rater = new SongRater(); //cannot instantiate new timer when ui not rendered (e.g. behind a window) //just have it constantly tick instead SongTimer.Interval = 1000; SongTimer.Tick += SongTimer_Tick; SongTimer.Enabled = true; if (string.IsNullOrWhiteSpace(StartUpSong)) { textBoxMusicFolder.Text = Rater.PreviousFolder; PopulateSongs(textBoxMusicFolder.Text); } else { LoadStartupSong(StartUpSong); } var pipeListener = new NamedPipeListener <String>(); // instantiate an instance pipeListener.MessageReceived += PipeListener_MessageReceived; pipeListener.Error += (errSender, eventArgs) => MessageBox.Show($"Error ({eventArgs.ErrorType}): {eventArgs.Exception.Message}"); pipeListener.Start(); // when you're ready, start listening //TODO get saved mode Mode = PlaybackMode.Normal; buttonMode.Text = "Normal"; } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// Инициализация движка программы /// </summary> /// <returns></returns> public static bool InitEngine() { try { if (!SecurityHelper.CheckCertificateExists(StoreName.Root, StoreLocation.CurrentUser, Configuration.Mail.CertificateName)) { CreateMessage("Сертификат почтового сервера не установлен. Необходимо выполнить установку сертификата и повторно запустить программу", MessageType.Error, true, false, true); return(false); } // Инициализация параметров электронной почты MailHelper.Host = Configuration.Mail.Host; MailHelper.Domain = Configuration.Mail.Domain; MailHelper.ToRecipient = Configuration.Mail.ToRecipient; MailHelper.Username = Configuration.Mail.Username; MailHelper.Password = Configuration.Mail.Password; // Инициализация параметров ftp сервера FtpHelper.Host = Configuration.Ftp.Host; FtpHelper.Port = Configuration.Ftp.Port; FtpHelper.Cwd = Configuration.Ftp.Cwd; FtpHelper.Username = Configuration.Ftp.Username; FtpHelper.Password = Configuration.Ftp.Password; // Инициализация параметров SQL if (!IOHelper.IsFullPath(Configuration.Sql.Database)) { Configuration.Sql.Database = Path.Combine(CurrentDirectory, Configuration.Sql.Database); } SQLHelper.ConnectionString = string.Format("User={0};Password={1};Database={2};DataSource={3};Pooling=false;Connection lifetime=60;Charset=WIN1251;", Configuration.Sql.Username, Configuration.Sql.Password, Configuration.Sql.Database, Configuration.Sql.DataSource); // Проверка временных папок на их существование TempPath = Path.Combine(CurrentDirectory, "Temp"); if (!Directory.Exists(TempPath)) { Directory.CreateDirectory(TempPath); } TempTasksPath = Path.Combine(TempPath, "Tasks"); if (!Directory.Exists(TempTasksPath)) { Directory.CreateDirectory(TempTasksPath); } TempFtpPath = Path.Combine(TempPath, "Ftp"); if (!Directory.Exists(TempFtpPath)) { Directory.CreateDirectory(TempFtpPath); } TempSqlPath = Path.Combine(TempPath, "Sql"); if (!Directory.Exists(TempSqlPath)) { Directory.CreateDirectory(TempSqlPath); } // Проверка задач по обработке файлов CreateMessage("Загрузка задач...", MessageType.Information, false, false, true); StringBuilder errors = new StringBuilder(); foreach (Task task in Configuration.Tasks) { task.Name = task.Name.ToUpper(); task.Source = Environment.ExpandEnvironmentVariables(task.Source); if (!string.IsNullOrWhiteSpace(task.ExternalLib)) { task.ExternalLibAsm = Assembly.LoadFile(Path.Combine(CurrentDirectory, Environment.ExpandEnvironmentVariables(task.ExternalLib))); } if (!task.AllowDuplicate) { try { SQLHelper.CreateTableFingerprint(task.Name); } catch (Exception ex) { errors.AppendLine(string.Format("Ошибка: {0}", ex.ToString())); } } try { IOHelper.IsPathDirectory(task.Source); } catch (Exception ex) { if (ex is FileNotFoundException || ex is DirectoryNotFoundException) { errors.AppendLine(string.Format("Путь '{0}' для задачи '{1}' не существует", task.Source, task.Name)); continue; } throw; } } if (errors.Length > 0) { CreateMessage("Ошибка при инициализации задач:\r\n" + errors.ToString(), MessageType.Error, false, true, true); } try { // Проверка существования таблицы для хранения данных об обработанных файлах SQLHelper.CreateTableOperationInfo(); } catch (Exception ex) { CreateMessage("Ошибка при инициализации программы:\r\n" + ex.ToString(), MessageType.Error, false, true, true); } // Настройка главного таймера int interval = Configuration.TaskInterval; MainTimer = new Timer(); MainTimer.Interval = Math.Max(MinimumMainTimerInterval, interval); // Настройка таймера обновлений UpdateTimer = new System.Threading.Timer((s) => CheckUpdates(), null, 0, Math.Max(MinimumUpdateTimerInterval, Configuration.CheckUpdateInterval)); CreateMessage("Инициализация и запуск именованного канала...", MessageType.Information, false, false, true); NamedPipeListener <string> namedPipeListener = new NamedPipeListener <string>(ProductName); namedPipeListener.MessageReceived += delegate(object sender, NamedPipeListenerMessageReceivedEventArgs <string> e) { switch (e.Message) { case "force": TasksHelper.RunTasksThread(); break; default: break; } }; namedPipeListener.Error += delegate(object sender, NamedPipeListenerErrorEventArgs e) { CreateMessage(string.Format("Ошибка Pipe: ({0}): {1}", e.ErrorType, e.Exception.Message), MessageType.Error, false, false, true); }; namedPipeListener.Start(); new System.Threading.Timer(delegate(object state) { if (!UpdatesHelper.VersionSended) { CreateMessage("Отправка информации о текущей версии программы на сервер обновлений...", MessageType.Information, false, false, true); System.Threading.Thread thread = new System.Threading.Thread(delegate() { try { string errorString; if (!UpdatesHelper.SendVersionInformation(Configuration.Updates.ServerName, Configuration.ZipCode, ProductName, Version, out errorString)) { throw new Exception(errorString); } UpdatesHelper.VersionSended = true; } catch (Exception ex) { UpdatesHelper.VersionSended = false; CreateMessage("Ошибка при отправке информации о текущей версии программы:\r\n" + ex.ToString(), MessageType.Error, false, false, true); } }); thread.Start(); } }, null, 0, Math.Max(MinimumUpdateTimerInterval, Configuration.CheckUpdateInterval)); return(true); } catch (Exception ex) { CreateMessage("Ошибка инициализации программы:\r\n" + ex.ToString(), MessageType.Error, true, true, true); return(false); } }
/// <summary>Sends the specified <paramref name="message" /> to the default named pipe for the message.</summary> /// <param name="message">The message to send.</param> public static void SendMessage(TMessage message) { NamedPipeListener <TMessage> .SendMessage(DEFAULT_PIPENAME, message); }
private static void Main(string[] argc) { try { if (!AppHelper.PreInit()) { return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Assembly execAssembly = Assembly.GetExecutingAssembly(); AppHelper.GUID = ((GuidAttribute)execAssembly.GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value; string mutexId = string.Format("Global\\{{{0}}}", AppHelper.GUID); bool createdNew; MutexAccessRule allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); MutexSecurity securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); using (Mutex mutex = new Mutex(false, mutexId, out createdNew, securitySettings)) { bool hasHandle = false; try { try { hasHandle = mutex.WaitOne(3000, false); if (hasHandle == false) { if (AppHelper.ARGS.FirstOrDefault(x => x.ToLower() == "-f") != null) { AppHelper.CreateMessage("Выполнен запуск по требованию", MessageType.Information); NamedPipeListener <string> .SendMessage(AppHelper.ProductName, "force"); } else { MessageBox.Show("Программа уже запущена", AppHelper.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } return; } } catch (AbandonedMutexException err) { AppHelper.CreateMessage("Ошибка синхронизации Mutex: " + err.ToString(), MessageType.Error, true); hasHandle = true; } if (CheckDependencies()) { if (!SecurityHelper.IsAdministrator()) { AppHelper.CreateMessage("Программу необходимо запускать от имени администратора", MessageType.Error, true); return; } Application.Run(new MainForm()); } else { AppHelper.CreateMessage("Неверная версия Feodosiya.Lib.dll. Необходимая версия: >=" + MinFeodosiyaLibVer, MessageType.Error, true); return; } } finally { if (hasHandle) { mutex.ReleaseMutex(); } } } } catch (Exception ex) { AppHelper.CreateMessage(ex.ToString(), MessageType.Error, true); } }