private void metroButton1_Click(object senderr, EventArgs e) { //Отправить сообщение this.chatTextBox.AppendText("ВЫ: " + MessageTextBox.Text); if (LocalMachines.ListLocalMachines.Count == 0) { LogApplication.WriteLog($"Сообщение не отправленно, т.к. клиентов нет"); } UdpClient sender = new UdpClient(); // создаем UdpClient для отправки foreach (LocalMachine machine in LocalMachines.ListLocalMachines) { IPEndPoint endPoint = new IPEndPoint(machine.RemoteIp, Config.GlobalChatUdpPort); try { byte[] data = Config.Encoder.GetBytes(MessageTextBox.Text); sender.Send(data, data.Length, endPoint); // отправка } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { sender.Close(); } } MessageTextBox.Text = ""; }
public static void Log( LogApplication la = LogApplication.Dashboard, string logger = "", string message = "", string ipAddress = "" ) { try { var _repository = new LogRepository(); var model = new LogViewModel { Application = la.ToFriendlyString(), Logger = logger, Level = LogLevel.None.ToString(), Message = message, IpAddress = ipAddress, TimeStamp = DateTimeOffset.Now }; _repository.Add(model); } catch (Exception) { // Logger 때문에 발생하는 예외는 무시 } }
protected void btnSave_Click(object sender, EventArgs e) { LogApplication logApplication = new LogApplication(); LogEntity logEntity = new LogEntity(); logEntity.logType = LogType.ModifyPassword; logEntity.operatingTime = DateTime.Now; logEntity.currentUserId = UserInfo.UserID; logEntity.referrer = Context.Request.UrlReferrer.ToString(); logEntity.iPAddress = HttpContext.Current.Request.UserHostAddress; bool result; string msg = CheckInput(out result); if (!result) { ShowMessageToClient(msg, 2, false, false); return; } UsersEntity user = GetEntity(); int id = userApp.AddUser(user); if (id > 0) { //ShowSuccessMessageToClient(); Redirect("/Admin/users/ClientUserDetail.aspx?id=" + id + "&returnurl=/admin/Users/users.aspx", true); } else { ShowFailMessageToClient(userApp.BrokenRuleMessages); } }
public static void Init() { LogApplication.WriteLog("***InitConfig***"); { LogApplication.WriteLog(" Load file"); if (!File.Exists("conf.txt")) { LogApplication.WriteLog(" Create config file"); FileStream newConfFile = File.Create("conf.txt"); newConfFile.Write(Encoding.Unicode.GetBytes("Default\n1"), 0, 18); newConfFile.Close(); } StreamReader reader = new StreamReader("conf.txt"); nickname = reader.ReadLine(); LogApplication.WriteLog($" Load nickname -> {nickname}"); enableSound = reader.ReadLine() == "1" ? true : false; LogApplication.WriteLog($" Sound -> {enableSound}"); reader.Close(); } if (enableSound) { OnFoundNewComputer = null; OnCloseConnect = null; OnReceiveFile = null; OnOpenConnect = null; LogApplication.WriteLog("***End init players, sound off***"); } else { if (File.Exists("Others/OnFoundComputer.wav")) { OnFoundNewComputer = new SoundPlayer("Others/OnFoundComputer.wav"); LogApplication.WriteLog(" Loaded OnFoundComputer.wav"); } if (File.Exists("Others/OnReceiveFile.wav")) { OnReceiveFile = new SoundPlayer("Others/OnReceiveFile.wav"); LogApplication.WriteLog(" Loaded OnReceiveFile.wav"); } if (File.Exists("Others/OnOpenConnect.wav")) { OnOpenConnect = new SoundPlayer("Others/OnOpenConnect.wav"); LogApplication.WriteLog(" Loaded OnOpenConnect.wav"); } if (File.Exists("Others/OnCloseConnect.wav")) { OnCloseConnect = new SoundPlayer("Others/OnCloseConnect.wav"); LogApplication.WriteLog(" Loaded OnCloseConnect.wav"); } } LogApplication.WriteLog("***EndInitConfig***"); }
protected void btnLogin_Click(object sender, EventArgs e) { LogApplication logApplication = new LogApplication(); LogEntity logEntity = new LogEntity(); logEntity.logType = LogType.Login; logEntity.operatingTime = DateTime.Now; logEntity.referrer = Context.Request.UrlReferrer.ToString(); logEntity.iPAddress = HttpContext.Current.Request.UserHostAddress; UsersEntity user = userApp.Login(txtUserName.Text, txtPassword.Text); if (user == null) { string msg = FormatMessages(userApp.BrokenRuleMessages); //log fail logEntity.IsSuccess = false; logEntity.currentUserId = -1; logEntity.Description = "login fail. user name: " + txtUserName.Text + " password: "******"/Login.aspx?uname=" + txtUserName.Text); return; } LoginSystem(user, txtPassword.Text, chkRemember.Checked); //log success logEntity.IsSuccess = true; logEntity.currentUserId = user.UserID; logEntity.Description = user.UserName + " login success. "; logApplication.Write(logEntity); Response.Redirect("/Default.aspx"); }
private void добавитьФайлToolStripMenuItem_Click(object sender, EventArgs e) { AddFileDialog.ShowDialog(); if (AddFileDialog.FileNames.Length == 0) { return; } int index = pathFiles.Length; Array.Resize(ref pathFiles, pathFiles.Length + AddFileDialog.FileNames.Length); foreach (string a in AddFileDialog.FileNames) { ListViewItem item = this.FilesList.Items.Add((this.FilesList.Items.Count + 1).ToString()); item.SubItems.Add(a.Substring(a.LastIndexOf('\\') + 1)); FileInfo fileInfo = new FileInfo(a); item.SubItems.Add((fileInfo.Length / 1000000.0).ToString() + " МБ"); item.SubItems.Add("Готов к отправке"); pathFiles[index++] = a; LogApplication.WriteLog("[SendFileForm] В список к отправке добавлен файл " + a); } }
static void senderr() { LogApplication.WriteLog("[senderr] Поток рассылки активен"); while (true) { try { foreach (string bufff in ListIp) { string buff = bufff.Substring(0, bufff.LastIndexOf('.') + 1); for (int a = 0; a < 256; a++) { MyUdpSender.Send(Config.Encoder.GetBytes(Config.nickname), Config.Encoder.GetBytes(Config.nickname).Length, new IPEndPoint(IPAddress.Parse(buff + a), Config.UDP_ACTIVITY)); } } } catch (Exception ex) { LogApplication.WriteLog("[senderr] Произошло исключение ->" + ex.Message); LogApplication.WriteLog("[senderr] Сервис остановлен"); return; } Thread.Sleep(5000); } }
private void GlobalChatForm_FormClosing(object senderr, FormClosingEventArgs e) { NetworkModule.ChatForm = null; if (LocalMachines.ListLocalMachines.Count == 0) { LogApplication.WriteLog($"Сообщение не отправленно, т.к. клиентов нет"); } UdpClient sender = new UdpClient(); // создаем UdpClient для отправки foreach (LocalMachine machine in LocalMachines.ListLocalMachines) { IPEndPoint endPoint = new IPEndPoint(machine.RemoteIp, Config.GlobalChatUdpPort); try { byte[] data = Config.Encoder.GetBytes(Config.GlobalChatExitMessage); sender.Send(data, data.Length, endPoint); // отправка } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { sender.Close(); } } }
public static string ToFriendlyString(this LogApplication la) { string r = ""; switch (la) { case LogApplication.Dashboard: r = "대시보드"; break; case LogApplication.LogManager: r = "로그 관리자"; break; case LogApplication.CommunityManager: r = "커뮤니티 관리자"; break; case LogApplication.BoardManager: r = "게시판 관리자"; break; case LogApplication.CommentManager: r = "댓글 관리자"; break; case LogApplication.UserManager: r = "사용자 관리자"; break; case LogApplication.GroupManager: r = "그룹 관리자"; break; case LogApplication.MenuManager: r = "메뉴 관리자"; break; case LogApplication.StatisticsManager: r = "통계 관리자"; break; case LogApplication.ChatManager: r = "채팅 관리자"; break; case LogApplication.EventManager: r = "이벤트 관리자"; break; default: r = "대시보드"; break; } return(r); }
private void удалитьФайлToolStripMenuItem_Click(object sender, EventArgs e) { if (FilesList.SelectedItems.Count == 0) { return; } this.pathFiles[FilesList.SelectedItems[0].Index] = ""; LogApplication.WriteLog("[SendFileForm] Из списка к отправке удалён файл " + this.FilesList.SelectedItems[0].SubItems[1].Text); this.FilesList.SelectedItems[0].Remove(); }
static private void GlobalChatReceive() { Log.LogApplication.WriteLog($"[UDP Reader Worker] Старт потока глобального чата на порту {Config.GlobalChatUdpPort}"); /*=========*/ MyUdpClient1 = new UdpClient(Config.GlobalChatUdpPort); MyUdpClient1.JoinMulticastGroup(MulticastGroup, 20); IPEndPoint remoteIp = null; string localAddress = LocalIp; try { while (true) { byte[] data = MyUdpClient1.Receive(ref remoteIp); // получаем данные if (remoteIp.Address.ToString().Equals(localAddress)) { continue; } string message = Encoding.Unicode.GetString(data); if (message.Length <= 1) { continue; } if (ChatForm == null || !ChatForm.ShownForm) { LogApplication.WriteLog("[GlobalMessage] Форма не открыта, пропуск"); continue; } LogApplication.WriteLog($"[GlobalMessage] размер буффера {message.Length}, буффер в строку -> {message}"); ChatForm.Invoke((MethodInvoker) delegate { ChatForm.chatTextBox.AppendText(LocalMachines.GetNicknameByIP(IPAddress.Parse(remoteIp.ToString().Substring(0, remoteIp.ToString().IndexOf(':')))) + ": " + message); }); Thread.Sleep(2); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { MyUdpClient.Close(); } /*=========*/ }
protected void btnSave_Click(object sender, EventArgs e) { LogApplication logApplication = new LogApplication(); LogEntity logEntity = new LogEntity(); logEntity.logType = LogType.ModifyPassword; logEntity.operatingTime = DateTime.Now; logEntity.currentUserId = UserInfo.UserID; logEntity.referrer = Context.Request.UrlReferrer.ToString(); logEntity.iPAddress = HttpContext.Current.Request.UserHostAddress; bool result; string msg = CheckInput(out result); if (!result) { BaseWebsitePage.ShowMessageToClient(msg, 2, false, false); return; } UsersEntity user = GetEntity(); if (IsAdd) { int id = userApp.AddUser(user); if (id > 0) { BaseWebsitePage.ShowSuccessMessageToClient(); } else { BaseWebsitePage.ShowFailMessageToClient(userApp.BrokenRuleMessages); } } else { if (userApp.UpdateUser(user)) { BaseWebsitePage.ShowSuccessMessageToClient(false, true); logEntity.IsSuccess = true; logEntity.Description = UserInfo.UserName + " modifiy " + txtUserName.Text + " password to" + txtPassword.Text + " success. new password: "******" modifiy " + txtUserName.Text + " password to" + txtPassword.Text + " fail. msg: " + msg; } logApplication.Write(logEntity); } }
private void LocalChatText_KeyDown(object sender, KeyEventArgs e) { if (LocalChatText.Text.Length <= 1) { return; } if (e.KeyData.ToString() == "Return") { LogApplication.WriteLog($"[Передача файла EVENT] Передача клиенту сообщения {LocalChatText.Text} машине {RemoteIp.ToString()}"); string sendBuff = $"2{Config.nickname}:{LocalChatText.Text}"; client.Send(Config.Encoder.GetBytes(sendBuff), Config.Encoder.GetBytes(sendBuff).Length, RemoteIp.ToString(), Config.UDP_FILE_NAME_RECEIVE); this.LocalChat.AppendText("ВЫ: " + LocalChatText.Text); this.LocalChatText.Text = ""; } }
private void Form1_Load(object sender, EventArgs e) { try { LogApplication.Init(); Config.Init(); flag = true; } catch { MessageBox.Show("Один экземпляр уже запущен"); this.Close(); } if (DateTime.Now.Hour >= 19 || DateTime.Now.Hour < 8) StyleManager.Theme = MetroThemeStyle.Dark; }
static public void CheckMachines() { LogApplication.WriteLog("[PingCheck] работает, проверка существования клиентов в сети каждые 5 секунд"); Ping ping = new Ping(); while (true) { for (int a = 0; a < LocalMachines.ListLocalMachines.Count; a++) { try { PingReply reply = ping.Send(LocalMachines.ListLocalMachines[a].RemoteIp); if (reply.Status != IPStatus.Success) { bool result = false; for (int aa = 0; aa < 3; aa++) { reply = ping.Send(LocalMachines.ListLocalMachines[a].RemoteIp); if (reply.Status == IPStatus.Success) { result = true; break; } } if (!result) { LogApplication.WriteLog("[PingCheck] Обнаружена машина, которая недоступна, удаление"); LocalMachines.RemoveMachine(LocalMachines.ListLocalMachines[a].RemoteIp); break; } } } catch (Exception ex) { LogApplication.WriteLog($"[PingCheck] Исключение \n{ex.Message}\nSTACK\n{ex.StackTrace}\n[PingCheck] Удаляю машину {LocalMachines.ListLocalMachines[a].ComputerNickname}:{LocalMachines.ListLocalMachines[a].RemoteIp.ToString()}"); } } Thread.Sleep(TimeSpan.FromSeconds(5)); } }
protected void btnSave_Click(object sender, EventArgs e) { LogApplication logApplication = new LogApplication(); LogEntity logEntity = new LogEntity(); logEntity.logType = LogType.ModifyPassword; logEntity.operatingTime = DateTime.Now; logEntity.currentUserId = UserInfo.UserID; logEntity.referrer = Context.Request.UrlReferrer.ToString(); logEntity.iPAddress = HttpContext.Current.Request.UserHostAddress; UsersEntity model = UserInfo; string msg = CheckInput(); if (string.IsNullOrEmpty(msg)) { model.PassWord = txtPassword.Text; if (userApp.UpdateUser(model)) { BaseWebsitePage.ShowSuccessMessageToClient(false, false); logEntity.IsSuccess = true; logEntity.Description = UserInfo.UserName + " modifiy own password to" + txtPassword.Text + " success. "; logApplication.Write(logEntity); } else { BaseWebsitePage.ShowFailMessageToClient(userApp.BrokenRuleMessages); logEntity.IsSuccess = false; logEntity.Description = UserInfo.UserName + " modifiy own password to" + txtPassword.Text + " fail. "; logApplication.Write(logEntity); } } else { BaseWebsitePage.ShowMessageToClient(msg, 2, false, false); logEntity.IsSuccess = false; logEntity.Description = UserInfo.UserName + " modifiy own password to" + txtPassword.Text + " fail. " + msg; logApplication.Write(logEntity); } }
private void metroButton1_Click(object sender, EventArgs e) { try { string buff = this.metroCheckBox1.Checked ? "1" : "0"; LogApplication.WriteLog($"Запись новых настроек \n{this.metroTextBox1.Text}\n{buff}\nEND NEW SETTINGS"); File.WriteAllText("conf.txt", $"{this.metroTextBox1.Text}\n{buff}"); new PopupNotifier() { TitleText = "Настройки", ContentText = "Новые настройки были успешно сохранены" }.Popup(); this.Close(); } catch (Exception ex) { MessageBox.Show("Произошла непредвиденная ошибка"); LogApplication.WriteLog(ex.Message); } }
/// <summary> /// Write Login log. /// </summary> /// <param name="isLoginSuccess">is loin success</param> /// <param name="currentUserId">current login user id ,if login fail then -1</param> /// <param name="loginUserName"></param> /// <param name="password"></param> private void WriteLoginLog(bool isLoginSuccess, int currentUserId, string loginUserName, string password) { LogApplication logApplication = new LogApplication(); LogEntity logEntity = new LogEntity(); logEntity.logType = LogType.Login; logEntity.operatingTime = DateTime.Now; logEntity.referrer = Context.Request.UrlReferrer.ToString(); logEntity.iPAddress = HttpContext.Current.Request.UserHostAddress; logEntity.IsSuccess = false; logEntity.currentUserId = -1; if (isLoginSuccess) { logEntity.Description = loginUserName + " login success. "; } else { logEntity.Description = "login fail. user name: " + loginUserName + " password: " + password; } logApplication.Write(logEntity); }
private void SendFiles_Button_Click(object sender, EventArgs e) { SendFile_Progress.Maximum = FilesList.Items.Count; for (int a = 0; a < FilesList.Items.Count; a++) { if (File.Exists(pathFiles[a])) { FilesList.Items[a].SubItems[3].Text = "Передача"; Label_State.Text = FilesList.Items[a].SubItems[1].Text; Label_State.Update(); LogApplication.WriteLog($"[SendFileForm] Начало передачи файла {pathFiles[a]}"); LogApplication.WriteLog($"[SendFileForm] Отправка предупреждения о начале передачи"); byte[] sendBuff = new byte[2 + FilesList.Items[a].SubItems[1].Text.Length]; sendBuff[0] = (byte)PacketIdentification.TransferFileRequest; sendBuff[1] = (byte)FilesList.Items[a].SubItems[1].Text.Length; Array.Copy(Config.Encoder.GetBytes(FilesList.Items[a].SubItems[1].Text), 0, sendBuff, 2, Config.Encoder.GetBytes(FilesList.Items[a].SubItems[1].Text).Length); NetworkModule.UdpClient.SendTo(sendBuff, new IPEndPoint(ip, Config.LocalPort)); Thread.Sleep(30); TcpClient tcpClient = new TcpClient(); for (int count = 0; count < 9; count++) { tcpClient.Connect(ip, 2229); if (!tcpClient.Connected) { break; } Thread.Sleep(10); Application.DoEvents(); } if (!tcpClient.Connected) { NetworkModule.GlavnForm.Invoke((MethodInvoker) delegate { PopupNotifier popp = new PopupNotifier() { TitleText = "FileExchange", ContentText = $"Соединение не установлено\n" }; popp.Popup(); }); break; } BinaryReader SendFileReader = new BinaryReader(new FileStream(pathFiles[a], FileMode.Open)); { PopupNotifier pop = new PopupNotifier() { TitleText = "FileExchange", ContentText = $"Соединение установленно, начало передачи" }; pop.Popup(); } NetworkStream stream = tcpClient.GetStream(); while (true) { stream.Write(SendFileReader.ReadBytes(200), 0, 200); if (SendFileReader.BaseStream.Position == SendFileReader.BaseStream.Length - 1) { //Конец передачи break; } } { PopupNotifier pop = new PopupNotifier() { TitleText = "FileExchange", ContentText = $"Соединение установленно, начало передачи" }; pop.Popup(); } tcpClient.Close(); SendFileReader.Close(); } //Thread.Sleep(1000); } }
private void FileTransfer_FormClosing(object sender, FormClosingEventArgs e) { UserCloseForm = true; client.Send(Config.Encoder.GetBytes("33aaaf"), Config.Encoder.GetBytes("33aaaf").Length, new IPEndPoint(RemoteIp, Config.UDP_FILE_NAME_RECEIVE)); Thread.Sleep(10); LogApplication.WriteLog("[Закрытие формы передачи файлов] Закрытие клиентов UPD и TCP"); { //Закрытие соединений client.Close(); MyUdpClient.Close(); tcpClient.Close(); } LogApplication.WriteLog("[Закрытие формы передачи файлов] Закрытие потоков"); { //Закрытие потоков if (UdpMessageReceiverHandler.ThreadState == ThreadState.Running) { UdpMessageReceiverHandler.Abort(); } if (TcpFileBytesReceiver.ThreadState == ThreadState.Running) { TcpFileBytesReceiver.Abort(); } } if (!RemoteUserClose && !UserCloseForm) { GlavnForm.Invoke((MethodInvoker) delegate { LogApplication.WriteLog("[Закрытие формы передачи файлов] Закрыто по неизвестной причине"); new PopupNotifier() { TitleText = "FileExchange", ContentText = $"Соединение закрыто по неизвестной причине" }.Popup(); }); } else if (RemoteUserClose) { GlavnForm.Invoke((MethodInvoker) delegate { LogApplication.WriteLog("[Закрытие формы передачи файлов] Удалённый комп сам закрыл соединение"); new PopupNotifier() { TitleText = "FileExchange", ContentText = $"Удалённый компьютер закрыл соединение с вами" }.Popup(); }); } else if (UserCloseForm) { LogApplication.WriteLog("[Закрытие формы передачи файлов] Мы сами закрыли соединение"); GlavnForm.Invoke((MethodInvoker) delegate { new PopupNotifier() { TitleText = "FileExchange", ContentText = $"Закрыл соединение с удалённым компом" }.Popup(); }); } }
public void TcpBytesReaderFunc() { LogApplication.WriteLog("[TcpBytesReader] Активен и ждёт пакеты по TCP"); long ReceiveBytes = 0; try { while (true) { using (var stream = tcpClient.GetStream()) { LogApplication.WriteLog("[TcpBytesReader] Клиент подключен. Начинаю приём байтов файла"); // чтение 1 килобайта var buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0) { try { LogApplication.WriteLog($"[TcpBytesReader] read > 0, -> {bytesRead}, write to stream...."); FileWriter.Write(buffer, 0, bytesRead); LogApplication.WriteLog($"[TcpBytesReader] write {bytesRead} bytes to stream success"); //ReceiveBytes += bytesRead; //LogApplication.WriteLog($"[TcpBytesReader] Receive bytes {bytesRead}/ ALL {ReceiveBytes}"); } catch (Exception ex) { LogApplication.WriteLog("[TcpBytesReader] reading exception " + ex.Message); } } } } } catch (Exception ex) { LogApplication.WriteLog($"[TcpBytesReader] Исключение \n{ex.Message} \n {ex.StackTrace} \n**************************"); GlavnForm.Invoke((MethodInvoker) delegate { if (!UserCloseForm) { new PopupNotifier() { TitleText = "FileExchange", ContentText = $"[TcpBytesReader] Возникла ошибка, связь была потерянна", Delay = 10 }.Popup(); } }); if (!UserCloseForm) { this.Invoke((MethodInvoker) delegate { this.Close(); }); } } }
private void UdpConnMessageHandler() { LogApplication.WriteLog("[UdpConnMessageHandler] Хандлер приёма имени файла по UDP активен"); IPEndPoint remoteIp = null; MyUdpClient = new UdpClient(Config.UDP_FILE_NAME_RECEIVE); try { while (true) { byte[] data = MyUdpClient.Receive(ref remoteIp); // получаем данные string fileName = Encoding.Unicode.GetString(data); if (fileName.Length <= 2) { continue; } if (fileName[0] == '1') { //Сообщение, сигнал о приёме файла fileName = fileName.Substring(1, fileName.Length - 1); LogApplication.WriteLog($"[UdpConnMessageHandler] ->{fileName}<- открываю на запись"); GlavnForm.Invoke((MethodInvoker) delegate { new PopupNotifier() { TitleText = "FileExchange", ContentText = $"Приём файла {fileName}" }.Popup(); }); FileWriter = new BinaryWriter(new FileStream("Files\\" + fileName, FileMode.Create)); ReceiveFileNameBuffer = fileName; ListViewItem item = this.FilesList.Items.Add((this.FilesList.Items.Count + 1).ToString()); item.SubItems.Add(fileName); item.SubItems.Add((FileWriter.BaseStream.Length / 1000000) + " МБайт"); item.SubItems.Add("Принимаю"); } else if (fileName[0] == '0') { //Сигнал, окончание приёма LogApplication.WriteLog($"[UdpConnMessageHandler] Закрываю запись"); FileWriter.Close(); setReceiveEnd(ReceiveFileNameBuffer); GlavnForm.Invoke((MethodInvoker) delegate { PopupNotifier popup = new PopupNotifier() { TitleText = "FileExchange", ContentText = $"Завершен приём файла {ReceiveFileNameBuffer}" }; popup.Click += ClickPopupOnReceiveEnd; popup.Popup(); Config.OnReceiveFile.Play(); }); } else if (fileName[0] == '2') { //Сообщение локального чата LogApplication.WriteLog("[UdpConnMessageHandler] Принял сообщение локального чата -> " + fileName); this.LocalChat.AppendText(fileName.Substring(1, fileName.Length - 1)); } else if (fileName[0] == '3') { //Закрытие соединения LogApplication.WriteLog("[UdpConnMessageHandler] Удалённый компьютер прислал сообщение о том, что пользователь закрывает форму"); this.RemoteUserClose = true; Config.OnCloseConnect.Play(); } else if (fileName[0] == '4') { //Размер пакета this.FilesList.Items[this.FilesList.Items.Count - 1].SubItems[2].Text = fileName.Substring(1, fileName.Length - 1) + " МБайт"; } else { LogApplication.WriteLog($"[WARNING] -------> Принял неизвестный пакет ->{fileName}<-"); } Thread.Sleep(2); } } catch (Exception ex) { LogApplication.WriteLog("[UdpConnMessageHandler] " + ex.Message); } finally { MyUdpClient.Close(); } LogApplication.WriteLog("[UdpConnMessageHandler] Конец работы"); }
private void передатьФайлToolStripMenuItem_Click(object sender, EventArgs e) { LogApplication.WriteLog("\n\n[Передача файла EVENT] Открытие диалога выбора файла"); this.TransferFile_Progress.Value = 0; Label_State.Text = "Выбор файла"; GlavnForm.Invoke((MethodInvoker) delegate { AddFileDialog.ShowDialog(); }); LogApplication.WriteLog("[Передача файла EVENT] Проверка количества выбранных файлов"); if (AddFileDialog.FileNames.Length == 0) { LogApplication.WriteLog("[Передача файла EVENT] Файлы не были выбранны"); return; } LogApplication.WriteLog("[Передача файла EVENT] Создание item'a в таблице"); ListViewItem item = this.FilesList.Items.Add((this.FilesList.Items.Count + 1).ToString()); item.SubItems.Add(AddFileDialog.FileNames[0].Substring(AddFileDialog.FileNames[0].LastIndexOf('\\') + 1)); FileInfo fileInfo = new FileInfo(AddFileDialog.FileNames[0]); item.SubItems.Add((fileInfo.Length / 1000000f).ToString() + " МБ"); item.SubItems.Add("Отправляется"); LogApplication.WriteLog("[Передача файла EVENT] ApplicationDoEvents"); Application.DoEvents(); client = new UdpClient(); string buffer = "1" + AddFileDialog.FileNames[0].Substring(AddFileDialog.FileNames[0].LastIndexOf('\\') + 1, AddFileDialog.FileNames[0].Length - AddFileDialog.FileNames[0].LastIndexOf('\\') - 1); LogApplication.WriteLog($"[Передача файла EVENT] Передача клиенту названия файла {buffer}"); { Label_State.Text = "Передача названия файла"; client.Send(Config.Encoder.GetBytes(buffer), Config.Encoder.GetBytes(buffer).Length, RemoteIp.ToString(), Config.UDP_FILE_NAME_RECEIVE); } LogApplication.WriteLog($"[Передача файла EVENT] Передача клиенту размера файла"); { buffer = $"4{fileInfo.Length / 1000000f}"; client.Send(Config.Encoder.GetBytes(buffer), Config.Encoder.GetBytes(buffer).Length, RemoteIp.ToString(), Config.UDP_FILE_NAME_RECEIVE); } new Task(() => { LogApplication.WriteLog("[Передача файла EVENT] Передано, начинаю передачу по TCP -> " + AddFileDialog.FileNames[0] + "\n\n\n"); BinaryReader reader = new BinaryReader(new FileStream(AddFileDialog.FileNames[0], FileMode.Open)); this.TransferFile_Progress.Maximum = (int)reader.BaseStream.Length; long sendedBytes = 0; Label_State.Text = "Передача файла"; while (reader.BaseStream.Position < reader.BaseStream.Length) { try { byte[] ReadBytes = reader.ReadBytes(1024); tcpClient.GetStream().Write(ReadBytes, 0, ReadBytes.Length); sendedBytes += ReadBytes.Length; this.TransferFile_Progress.Value += ReadBytes.Length; LogApplication.WriteLog($"SEND bytes {ReadBytes.Length.ToString()}/{sendedBytes}"); LogApplication.WriteLog($"Stream position {reader.BaseStream.Position}/{reader.BaseStream.Length}\n"); } catch (Exception Ex) { LogApplication.WriteLog("[SendBytes] exception \n" + Ex.Message); } GlavnForm.Invoke((MethodInvoker) delegate { Label_State.Text = $"Идёт передача {reader.BaseStream.Position / (float)reader.BaseStream.Length * 100} из 100%"; }); } Thread.Sleep(300); LogApplication.WriteLog("[Передача файла EVENT] Типа передано, отправляю сигнал о закрытии потока"); client.Send(Config.Encoder.GetBytes("00zdkf"), Config.Encoder.GetBytes("00zdkf").Length, RemoteIp.ToString(), Config.UDP_FILE_NAME_RECEIVE); LogApplication.WriteLog("[Передача файла EVENT] Конец"); GlavnForm.Invoke((MethodInvoker) delegate { item.SubItems[3].Text = "Передано"; new PopupNotifier() { TitleText = "FileExchange", ContentText = $"Файл {item.SubItems[1].Text} успешно передан" }.Popup(); }); reader.Close(); }).Start(); }
/*================================================================================================*/ static public bool Add(IPAddress ip, string nickname = "") { Monitor.Enter(locker); foreach (LocalMachine machine in ListLocalMachines) { //Проверка, есть ли такая машина у нас в листе if (ip.ToString() == machine.RemoteIp.ToString()) { return(false); } } LocalMachine newMachine = new LocalMachine(); { newMachine.RemoteIp = ip; newMachine.trusted = false; newMachine.ComputerNickname = nickname.Length < 3 ? "Неизвестный маслёнок" : nickname; } if (ListLocalMachines.Count == 0) { MetroTile metroTilee = new MetroTile(); metroTilee.Location = new System.Drawing.Point(69, 69); metroTilee.Size = new System.Drawing.Size(175, 183); metroTilee.Name = newMachine.ComputerNickname; metroTilee.Text = newMachine.ComputerNickname; metroTilee.TabIndex = 23; metroTilee.ContextMenuStrip = NetworkModule.GlavnForm.contextMenuStrip1; metroTilee.MouseEnter += NetworkModule.GlavnForm.metroTile4_MouseEnter; metroTilee.TileImage = global::WindowsFormsApp1.Properties.Resources.computer_screen; metroTilee.TileImageAlign = System.Drawing.ContentAlignment.MiddleCenter; metroTilee.UseTileImage = true; newMachine.MachineFormTile = metroTilee; NetworkModule.GlavnForm.Invoke((MethodInvoker) delegate { NetworkModule.GlavnForm.Controls.Add(metroTilee); NetworkModule.GlavnForm.LABEL_START_WORK.Visible = false; }); } else { MetroTile metroTilee = new MetroTile(); metroTilee.Location = new System.Drawing.Point(ListLocalMachines[ListLocalMachines.Count - 1].MachineFormTile.Location.X + 175 + 30, ListLocalMachines[ListLocalMachines.Count - 1].MachineFormTile.Location.Y); metroTilee.Size = new System.Drawing.Size(175, 183); metroTilee.Name = newMachine.ComputerNickname; metroTilee.Text = newMachine.ComputerNickname; metroTilee.TabIndex = 23; metroTilee.ContextMenuStrip = NetworkModule.GlavnForm.contextMenuStrip1; metroTilee.MouseEnter += NetworkModule.GlavnForm.metroTile4_MouseEnter; metroTilee.TileImage = global::WindowsFormsApp1.Properties.Resources.computer_screen; metroTilee.TileImageAlign = System.Drawing.ContentAlignment.MiddleCenter; metroTilee.UseTileImage = true; newMachine.MachineFormTile = metroTilee; NetworkModule.GlavnForm.Invoke((MethodInvoker) delegate { NetworkModule.GlavnForm.Controls.Add(metroTilee); NetworkModule.GlavnForm.Size = new Size(NetworkModule.GlavnForm.Size.Width + 100, NetworkModule.GlavnForm.Size.Height); }); } ListLocalMachines.Add(newMachine); LogApplication.WriteLog($"Добавлена машина в список {ip.ToString()} с никнеймом {newMachine.ComputerNickname}"); if (Config.OnFoundNewComputer != null) { LogApplication.WriteLog("Воспроизведение звука OnFoundComputer"); Config.OnFoundNewComputer.Play(); } Monitor.Exit(locker); return(true); }
protected void btnSave_Click(object sender, EventArgs e) { LogApplication logApplication = new LogApplication(); LogEntity logEntity = new LogEntity(); logEntity.logType = LogType.ModifyPassword; logEntity.operatingTime = DateTime.Now; logEntity.currentUserId = UserInfo.UserID; logEntity.referrer = Context.Request.UrlReferrer.ToString(); logEntity.iPAddress = HttpContext.Current.Request.UserHostAddress; string msg = ""; if (!string.IsNullOrEmpty(txtPassword.Text) || !string.IsNullOrEmpty(txtConfirmPassword.Text)) { bool result; msg = CheckInput(out result); if (!result) { ShowMessageToClient(msg, 2, false, false); return; } } UsersEntity user = GetEntity(); List <WorkTimeEntity> workTimes = BuildWorkTime(); //if (user.CompanyID != UserToEdit.CompanyID) //{ // ShowFailMessageToClient("All projects Assiged on the company will be removed."); // return; //} if (userApp.UpdateUser(user)) { if (workTimes.Any()) { if (eventsApp.UpdateWorkTime(workTimes)) { ShowSuccessMessageToClient(false, true); logEntity.IsSuccess = true; logEntity.Description = UserInfo.UserName + " modifiy " + txtUserName.Text + " password to" + txtPassword.Text + " success. new password: "******" modifiy " + txtUserName.Text + " password to" + txtPassword.Text + " fail. msg: " + msg; } } else { if (eventsApp.DeleteWorkTimeByUserId(UserToEdit.UserID)) { ShowSuccessMessageToClient(false, true); logEntity.IsSuccess = true; logEntity.Description = UserInfo.UserName + " modifiy " + txtUserName.Text + " password to" + txtPassword.Text + " success. new password: "******" modifiy " + txtUserName.Text + " password to" + txtPassword.Text + " fail. msg: " + msg; } } } else { ShowFailMessageToClient(userApp.BrokenRuleMessages); logEntity.IsSuccess = false; logEntity.Description = UserInfo.UserName + " modifiy " + txtUserName.Text + " password to" + txtPassword.Text + " fail. msg: " + msg; } logApplication.Write(logEntity); }
static private void WaitConnectionThread() { //Ожидает и обрабатывает TCP подключения от компьютеров, которые нас обнаружили в сети LogApplication.WriteLog("[WaitConnectionThread] Ожидание подключения"); IPAddress localAddr = IPAddress.Parse("0.0.0.0"); TcpReceiveListener = new TcpListener(localAddr, Config.TCP_FILE_TRANSFER_PORT); TcpClient client = null; TcpReceiveListener.Start(); Thread.Sleep(3000); try { while (true) { if (client == null || !client.Connected) { GlavnForm.Invoke((MethodInvoker) delegate { new PopupNotifier() { TitleText = "FileExchange", ContentText = $"Ожидание TCP соединения" }.Popup(); }); LogApplication.WriteLog("[WaitTCPConnection] ожидание подключения"); client = TcpReceiveListener.AcceptTcpClient(); LogApplication.WriteLog("[WaitTCPConnection] подключение установлено"); GlavnForm.Invoke((MethodInvoker) delegate { new PopupNotifier() { TitleText = "FileExchange", ContentText = $"Подключение установленно" }.Popup(); }); FileTransfer fileTransfer = new FileTransfer(client, TcpReceiveListener, IPAddress.Parse(client.Client.RemoteEndPoint.ToString().Substring(0, client.Client.RemoteEndPoint.ToString().LastIndexOf(':'))), GlavnForm); fileTransfer.StyleManager.Theme = GlavnForm.StyleManager.Theme; if (fileTransfer.StyleManager.Theme == MetroThemeStyle.Dark) { fileTransfer.FilesList.BackColor = System.Drawing.SystemColors.ControlDarkDark; } LogApplication.WriteLog("[WaitTCPConnection] Открытие формы"); fileTransfer.ShowDialog(); } Thread.Sleep(1000); } } catch (Exception ex) { LogApplication.WriteLog("[WaitTCPConnection] Произошла ошибка " + ex.Message); } }
static public void Detect() { LogApplication.WriteLog("[Detect] Запущен"); IPEndPoint remoteIp = null; string localAddress = LocalIp; try { while (true) { byte[] data = MyUdpClient.Receive(ref remoteIp); // получаем данные { bool local = false; foreach (string bufff in ListIp) { if (remoteIp.Address.ToString().Equals(bufff)) { local = true; break; } } if (local) { continue; } } string message = Encoding.Unicode.GetString(data); if (message.Length <= 1) { continue; } if (LocalMachines.Add(IPAddress.Parse(remoteIp.ToString().Substring(0, remoteIp.ToString().IndexOf(':'))), message)) { GlavnForm.Invoke((MethodInvoker) delegate { new PopupNotifier() { TitleText = "FileExchange", ContentText = $"Новый компьютер в локальной сети {remoteIp.ToString().Substring(0, remoteIp.ToString().IndexOf(':'))}\n Никнейм {message}" }.Popup(); }); } Thread.Sleep(2); } } catch (Exception ex) { LogApplication.WriteLog($"DETECTOR ИСКЛЮЧЕНИЕ IP:{remoteIp.ToString()}\n\nMESSAGE\n{ex.Message}\n\nSTACK\n" + ex.StackTrace + "\n\n\n"); } finally { MyUdpClient.Close(); } LogApplication.WriteLog("[Detector] Конец работы детектора"); }
static public void Init(Form1 ff) { GlavnForm = ff; List <string> s = new List <string>(); string StringIp = ""; { //Выделение локального IP var host = Dns.GetHostEntry(Dns.GetHostName()); foreach (var ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { if (LocalIp == null) { LocalIp = ip.ToString(); } StringIp += "\n" + ip.ToString(); ListIp.Add(ip.ToString()); LogApplication.WriteLog("local ip ->" + ip.ToString()); } } } if (LocalIp == "127.0.0.1") { LogApplication.WriteLog("Нет доступных сетей кроме loopback, т.к. LocalIp == 127.0.0.1, создание задачи на попытку"); GlavnForm.Invoke((MethodInvoker) delegate { new PopupNotifier() { TitleText = "FileExchange", ContentText = $"Не доступных подключений, кроме локальной петли, проверьте подключение по LAN или Wifi" }.Popup(); }); return; } else { new Task(() => { Thread.Sleep(30000); GlavnForm.Invoke((MethodInvoker) delegate { new PopupNotifier() { TitleText = "FileExchange", ContentText = $"Локальные адреса: \n{StringIp}" }.Popup(); }); }).Start(); } GlavnForm.timerConnect.Enabled = false; ReceiveConnectionThread.Start(); Thread.Sleep(100); Sender.Start(); Thread.Sleep(100); GlobalChatReceiveThread.Start(); Thread.Sleep(100); Detector.Start(); PingThread.Start(); GlavnForm.Invoke((MethodInvoker) delegate { new PopupNotifier() { TitleText = "FileExchange", ContentText = $"Сервисы активны\n" }.Popup(); }); }