static readonly object lockerDir = new object(); //each thread server must access to an exclusive section one at time public void EntryPoint() { try // start both udp and tcp { threadUDP = new Thread(EntryUDP); threadUDP.IsBackground = true; threadUDP.Start(); threadTCP = new Thread(EntryTCP); threadTCP.IsBackground = true; threadTCP.SetApartmentState(ApartmentState.STA); threadTCP.Start(); } catch (Exception e) { Console.WriteLine(e.ToString()); LANSharingApp.LogFile(e.Message, e.ToString(), e.Source); // delegate the operation on form to the GUI MessageFormError mfe = new MessageFormError("UDP or TCP service not available"); LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfe.ShowDialog(); }); LANSharingApp.closing = true; LANSharingApp.serverThread.Join(); LANSharingApp.clearTempFiles(); LANSharingApp.flushTmpDirectory(); Application.Exit(); } }
// method used to remove old users from the list and from the GUI internal void RemoveOldUsers() { try { Dictionary <string, User> .ValueCollection All_Users = Online_Users.Values; if (All_Users != null && All_Users.Count > 0) { // use ToList in order to avoid the exception generated if we remove a person with the pointer to next person foreach (User user in All_Users.ToList <User>()) // foreach user { var isNew = user.isNew(); // True -> no button var isOld = user.isOld(); // True -> button not online if (isOld) // remove { LANSharingApp.gui.flowLayoutPanel.Controls.Remove(user.getButton()); Online_Buttons.Remove(user.getButton()); Console.WriteLine("Rimosso: " + user.getFirstName() + " " + user.getLastName()); Online_Users.Remove(user.getLastName() + user.getFirstName()); } } } } catch (Exception e) { Console.WriteLine(e.ToString()); LANSharingApp.LogFile(e.Message, e.ToString(), e.Source); LANSharingApp.serverThread.Join(); Application.Exit(); } }
// method called when the SendButton is clicked public void SendButtonClick() { try { if (Target_Buttons.Count > 0) // if targets are > 0 { foreach (MetroFramework.Controls.MetroTile metroButton in Target_Buttons) {// each thread will start with an argument = name of user Thread clientThread = new Thread(() => LANSharingApp.client.EntryPoint(metroButton.Name)) { Name = "clientThread" }; clientThread.IsBackground = true; clientThread.Start(); } } else { MessageBox.Show("Please select an user"); if (LANSharingApp.sysSoundFlag == 1) { audio_error.Play(); } } clearMetroButtons(); } catch (Exception e) { Console.WriteLine(e.ToString()); LANSharingApp.LogFile(e.Message, e.ToString(), e.Source); LANSharingApp.serverThread.Join(); Application.Exit(); } }
internal void UpdateImageButtons() { try { Dictionary <string, User> .ValueCollection All_Users = Online_Users.Values; if (All_Users != null && All_Users.Count > 0) { foreach (User user in All_Users.ToList <User>()) { Bitmap b1 = new Bitmap(user.getImage()); Bitmap b2 = new Bitmap(user.getButton().TileImage); if (!ImageCompareString(b1, b2)) { //get button metroButton = user.getButton(); //remove obsolete button with old image LANSharingApp.gui.flowLayoutPanel.Controls.Remove(user.getButton()); //add new button with new image metroButton.TileImage = user.getImage(); LANSharingApp.gui.flowLayoutPanel.Controls.Add(metroButton); } } } } catch (Exception e) { Console.WriteLine(e.ToString()); LANSharingApp.LogFile(e.Message, e.ToString(), e.Source); LANSharingApp.serverThread.Join(); Application.Exit(); } }
public GUI(string selectedPath) { InitializeComponent(); try { //update user_image this.user_tile.TileImage = LANSharingApp.user_image; this.user_tile.Refresh(); // link menu to the task bar this.taskbarIcon.ContextMenuStrip = contextMenuTaskBar; // visualize admin info firstNameLabel.Text = LANSharingApp.umu.getAdmin().getFirstName(); lastNameLabel.Text = LANSharingApp.umu.getAdmin().getLastName(); lock (LANSharingApp.lockerPathSend) { //show path if (LANSharingApp.pathSend != null) { pathBox.Text = LANSharingApp.pathSend; } } //manage two possible state: Online/Offline if (LANSharingApp.umu.getAdmin().getState() == "online") { stateLabel.Text = "ONLINE"; offlineMenuItem.Checked = false; onlineMenuItem.Checked = true; state_offline_dot.Visible = false; state_online_dot.Visible = true; } else { stateLabel.Text = "OFFLINE"; offlineMenuItem.Checked = true; onlineMenuItem.Checked = false; state_offline_dot.Visible = true; state_online_dot.Visible = false; } // set timer for refresh button, in order to update the lsit of Online Users System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer(); timer.Interval = (1000); timer.Tick += new EventHandler(Timer_Tick_Tock); timer.Start(); } catch (Exception e) { Console.WriteLine(e.ToString()); LANSharingApp.LogFile(e.Message, e.ToString(), e.Source); } }
void OnUdpMessageReceived(object sender, MulticastUdpClient.UdpMessageReceivedEventArgs e) { try { string receivedText = ASCIIEncoding.ASCII.GetString(e.Buffer); string[] infoUser = receivedText.Split(','); //conversion //Console.WriteLine("UDP- ricevuto un pacchetto.: " + infoUser[0] + " " + infoUser[1]); // Console.WriteLine("UDP packet: " + infoUser[0] + ", " + infoUser[1] + ", " + infoUser[2] + " " + infoUser[3] + ", " + infoUser[4] + " " + infoUser[5]); Image userImage; userImage = Base64ToImage(infoUser[5]); if (LANSharingApp.umu.isPresent(infoUser[1] + infoUser[0])) { User u = new User(infoUser[0], infoUser[1], infoUser[2], infoUser[3], infoUser[4], userImage); //create new user if ((infoUser[2].CompareTo("online") == 0)) { // check if the user is already registered if (!u.isEqual(LANSharingApp.umu.getAdmin())) { LANSharingApp.umu.addUser(u); //add user } LANSharingApp.umu.resetUserTimer(infoUser[1] + infoUser[0]); // reset user timer } else { u.isOld(); } } else // user not in list { User p = new User(infoUser[0], infoUser[1], infoUser[2], infoUser[3], infoUser[4], userImage); //create new user if (!p.isEqual(LANSharingApp.umu.getAdmin())) { if (infoUser[2].CompareTo("online") == 0) //check not equal to admin { LANSharingApp.umu.addUser(p); //add user } } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); LANSharingApp.LogFile(ex.Message, ex.ToString(), ex.Source); LANSharingApp.closing = true; LANSharingApp.serverThread.Join(); LANSharingApp.clearTempFiles(); LANSharingApp.flushTmpDirectory(); Application.Exit(); } }
// use: 1) autoRefresh called by timer, without calling the buttonRefresh 2)called from the buttonRefresh private void Timer_Tick_Tock(object sender, EventArgs e) { try { //call the 2 methods thar update the list of Online Users LANSharingApp.umu.RemoveOldUsers(); LANSharingApp.umu.AddNewUsers(); LANSharingApp.umu.UpdateImageButtons(); //LAUNCH GUI WITH NEW PATH SEND IF THE USER INTERACT WITH NEW FILES/DIRECTORIES WITH RIGTH CLICK ON THEM //.... // read the integer value at position 500 MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor(); int l = accessor.ReadInt32(0); accessor.Flush(); // print it to the console if (l != 0) { //get path as bytes byte[] Buffer = new byte[l]; accessor.ReadArray(4, Buffer, 0, Buffer.Length); accessor.Flush(); //convert bytes to string string newPath = ASCIIEncoding.ASCII.GetString(Buffer); // Console.WriteLine("The newPath is " + newPath); lock (LANSharingApp.lockerPathSend) { LANSharingApp.pathSend = newPath; } this.pathBox.Text = newPath; LANSharingApp.umu.clearMetroButtons(); base.SetVisibleCore(true); this.WindowState = FormWindowState.Normal; //invalidate path as old one accessor.Write(0, 0); accessor.Flush(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); LANSharingApp.LogFile(ex.Message, ex.ToString(), ex.Source); } }
// start to notify wiht UDP packets the online presence public void EntryNotifyPresence() { try { while (!LANSharingApp.closing) { //check ethernet, need this line to generate exception!!! string localIP = LANSharingApp.umu.GetLocalIP(); //check if localIP == Admin.getIP if (!localIP.Equals(LANSharingApp.umu.getAdmin().getIp().ToString())) { LANSharingApp.umu.getAdmin().setIP(localIP); Console.WriteLine("Internet Network Changed: Restart Procedure."); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { Application.Restart(); }); } // send broadcast every 2s, only if ONLINE if (LANSharingApp.umu.getAdmin().getState().CompareTo("online") == 0) { sendBroadcastPacket(LANSharingApp.umu.getAdmin().getString()); //Console.WriteLine("UDP packet Admin: "+ LANSharingApp.umu.getAdmin().getString()); } // need a timer Thread.Sleep(2000); } } catch (Exception e) { Console.WriteLine(e.ToString()); LANSharingApp.LogFile(e.Message, e.ToString(), e.Source); LANSharingApp.closing = true; // delegate the operation on form to the GUI MessageFormError mfe = new MessageFormError("Error: no lan connection detected, connect to a lan then restart application."); LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfe.ShowDialog(); }); LANSharingApp.serverThread.Join(); LANSharingApp.clearTempFiles(); LANSharingApp.flushTmpDirectory(); Application.Exit(); } }
// search for a path save private void BrowseButton_Click(object sender, EventArgs e) { try { // need a lambda function with a new thread to perform operation // cause thread are MTA on launch Thread t = new Thread(() => { using (FolderBrowserDialog fbd = new FolderBrowserDialog()) { DialogResult dr = fbd.ShowDialog(); if (dr == DialogResult.OK) { lock (LANSharingApp.lockerPathSave) { LANSharingApp.pathSave = fbd.SelectedPath; } } } }); t.IsBackground = true; // must use STA for the new thread t.SetApartmentState(ApartmentState.STA); t.Start(); t.Join(); lock (LANSharingApp.lockerPathSave) { // update the path if (destinationPath.Text.CompareTo(LANSharingApp.pathSave) != 0) { destinationPath.Text = LANSharingApp.pathSave; // notify modification saveButton.Enabled = true; } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); LANSharingApp.LogFile(ex.Message, ex.ToString(), ex.Source); LANSharingApp.closing = true; LANSharingApp.serverThread.Join(); Application.Exit(); } }
static SoundPlayer audio_error = new SoundPlayer(LANSharing.Properties.Resources.Computer_Error); // here WindowsFormsApplication1 is the namespace and Connect is the audio file name public void EntryPoint(string userInfo) { // retrieve user credentials string[] credentials = userInfo.Split(','); try { User user = new User(); // firstname and lastname LANSharingApp.umu.getOnlineUsers().TryGetValue(credentials[1] + credentials[0], out user); if (user.isOnline()) { FTP_protocol(credentials[2], credentials[3], credentials[0], credentials[1]);// Ip and port } else { MessageFormError mfe = new MessageFormError(credentials[1] + " " + credentials[0] + " is offline!"); if (LANSharingApp.sysSoundFlag == 1) { audio_error.Play(); } // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfe.Show(); }); } } catch (Exception e) { // null reference to user Console.WriteLine(e.ToString()); LANSharingApp.LogFile(e.Message, e.ToString(), e.Source); if (LANSharingApp.sysSoundFlag == 1) { audio_error.Play(); } MessageFormError mfe = new MessageFormError(credentials[1] + " " + credentials[0] + " is offline!"); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfe.Show(); }); } }
public string GetLocalIP() { string localIP = null;; try { using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0)) { socket.Connect("8.8.8.8", 65530); IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint; localIP = endPoint.Address.ToString(); } //check if no connection if (localIP == null || !System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) { throw new Exception("No LAN connection detected"); } } catch (Exception e) { Console.WriteLine(e.ToString()); LANSharingApp.LogFile(e.Message, e.ToString(), e.Source); LANSharingApp.serverThread.Join(); Application.Exit(); } return(localIP); /* * string hostName = Dns.GetHostName(); // Retrive the Name of HOST * // Get the IP * string myIP = null; * int l = Dns.GetHostAddresses(Dns.GetHostName()).Length; * * if(l>0) * myIP = Dns.GetHostByName(hostName).AddressList[0].ToString(); * * if (myIP == null || !System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) * throw new Exception("No LAN connection detected"); * * return myIP; */ }
// method used to add new users on the list and on the GUI public void AddNewUsers() { try { Dictionary <string, User> .ValueCollection All_Users = Online_Users.Values; if (All_Users != null && All_Users.Count > 0) { foreach (User user in All_Users) { if (user.isNew() && user.isOnline()) { //sound // create button for user on the form metroButton = new MetroFramework.Controls.MetroTile(); metroButton.Name = user.getFirstName() + "," + user.getLastName() + "," + user.getIp() + "," + user.getPort(); metroButton.Text = user.getFirstName() + "\n" + user.getLastName(); metroButton.Style = MetroFramework.MetroColorStyle.Silver; // online but not selected //metroButton.TileImage = Image.FromFile("C:\\ProgramData\\Microsoft\\User Account Pictures\\user-32.png"); metroButton.TileImage = user.getImage(); metroButton.UseTileImage = true; metroButton.Size = new Size(70, 70); metroButton.TileImageAlign = ContentAlignment.TopCenter; metroButton.Click += new EventHandler(TargetUserButton_Click); Online_Buttons.Add(metroButton); user.addButton(metroButton); LANSharingApp.gui.flowLayoutPanel.Controls.Add(metroButton); user.unsetNew(); // user is not old but is not new now } } } }catch (Exception e) { Console.WriteLine(e.ToString()); LANSharingApp.LogFile(e.Message, e.ToString(), e.Source); LANSharingApp.serverThread.Join(); Application.Exit(); } }
// send udp packets for online-presence static void sendBroadcastPacket(string message) { // there is a problem with d-link router --> need this broadcat, not IPAddress.Broadcast IPEndPoint ipEP = new IPEndPoint(IPAddress.Broadcast, FTP_Port_send); try { udpClientWrapper.SendMulticast(ASCIIEncoding.ASCII.GetBytes(message)); } catch (Exception e) { Console.WriteLine("\n" + e.ToString()); LANSharingApp.LogFile(e.Message, e.ToString(), e.Source); LANSharingApp.closing = true; LANSharingApp.serverThread.Join(); LANSharingApp.clearTempFiles(); LANSharingApp.flushTmpDirectory(); Application.Exit(); } }
static SoundPlayer audio_error = new SoundPlayer(LANSharing.Properties.Resources.Computer_Error); // here WindowsFormsApplication1 is the namespace and Connect is the audio file name public UserManagerUnit() { try { // retrieve admin info and check LAN connection Online_Users = new Dictionary <string, User>(); string name = System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName; string[] adminInfo = name.Split(' '); // firstName and LastName string localIP = GetLocalIP(); admin = new User(adminInfo[0], adminInfo[1], "online", localIP, "3000", LANSharingApp.user_image); //set admin Console.WriteLine("admin info:" + adminInfo[0] + " " + adminInfo[1] + " " + localIP); } catch (Exception e) { Console.WriteLine(e.ToString()); LANSharingApp.LogFile(e.Message, e.ToString(), e.Source); LANSharingApp.closing = true; MessageBox.Show("Error: no lan connection detected, connect to a lan network then restart application.", "Error Detection Module", MessageBoxButtons.OK, MessageBoxIcon.Warning); Environment.Exit(0); } }
// EntryPoint of TCP operation public void EntryTCP() { try { // call only one time, on launch if (LANSharingApp.umu.getAdmin().isOnline() && !LANSharingApp.closing) { ReceiveFileProcedure(); } } catch (Exception e) { Console.WriteLine(e.ToString()); LANSharingApp.LogFile(e.Message, e.ToString(), e.Source); LANSharingApp.closing = true; LANSharingApp.serverThread.Join(); LANSharingApp.clearTempFiles(); LANSharingApp.flushTmpDirectory(); Application.Exit(); } }
private void onlineIconContextMenu_Click(object sender, EventArgs e) { // change the state online from the task bar try { if (!LANSharingApp.umu.getAdmin().isOnline()) { LANSharingApp.umu.changeAdminState("online"); LANSharingApp.mre.Set(); // unblock server with ManualResetEvent stateLabel.Text = "ONLINE"; offlineMenuItem.Checked = false; onlineMenuItem.Checked = true; state_offline_dot.Visible = false; state_online_dot.Visible = true; } } catch (Exception ex) { Console.WriteLine(ex.ToString()); LANSharingApp.LogFile(ex.Message, ex.ToString(), ex.Source); } }
private void Settings_FormClosing(object sender, FormClosingEventArgs e) { try { // ask if the user want really modify the form if (saveButton.Enabled) { if (LANSharingApp.sysSoundFlag == 1) { audio_error.Play(); } switch (MessageBox.Show(this, "Do you wanna save your changes?", "Exit from Settings", MessageBoxButtons.YesNo)) { case DialogResult.No: lock (LANSharingApp.lockerPathSave) { LANSharingApp.pathSave = lastPath; } break; default: Save_Click(sender, e); break; } } LANSharingApp.gui.settingsButton.Enabled = true; LANSharingApp.gui.settingsButton.Refresh(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); LANSharingApp.LogFile(ex.Message, ex.ToString(), ex.Source); LANSharingApp.closing = true; LANSharingApp.serverThread.Join(); Application.Exit(); } }
// EntryUDP start 2 thread: one for notify presence and one for detect other users on the LAN public void EntryUDP() { try { //create MulticastUdpClient udpClientWrapper = new MulticastUdpClient(multicastIPaddress, port, localIPaddress); udpClientWrapper.UdpMessageReceived += OnUdpMessageReceived; notifyPresenceUDP = new Thread(EntryNotifyPresence); notifyPresenceUDP.IsBackground = true; notifyPresenceUDP.Start(); } catch (Exception e) { Console.WriteLine(e.ToString()); LANSharingApp.LogFile(e.Message, e.ToString(), e.Source); LANSharingApp.closing = true; LANSharingApp.serverThread.Join(); LANSharingApp.clearTempFiles(); LANSharingApp.flushTmpDirectory(); Application.Exit(); } }
// It is the kernel of the FTP protocol Server side public void ProcessClientRequest(object argument) { byte[] buffer = Encoding.ASCII.GetBytes(""); string msg = ""; TcpClient client = (TcpClient)argument; BinaryWriter writer = null; BinaryReader reader = null; long check; string zipFileName = null; string zipDirName = null; string newName = null; if (!Directory.Exists(LANSharingApp.tmpPath)) { Directory.CreateDirectory(LANSharingApp.tmpPath); } try { using (NetworkStream networkStream = client.GetStream()) { writer = new BinaryWriter(networkStream); reader = new BinaryReader(networkStream); Console.WriteLine("[Server] - aspetto "); msg = reader.ReadString(); // receive header // username,usersurname, userip @ type @ path @ checkNumber Console.WriteLine("[Server] - ricevuto header: " + msg); string[] header = msg.Split('@'); string[] userInfo = header[0].Split(','); string type = header[1]; string fileName = header[2]; string currentPathSave = null; //each thread with profile 2 of Save can have different PathSave if (type.CompareTo("file") == 0) { if (LANSharingApp.saveProfile == 1) { // no automatic save, save on default path if (LANSharingApp.sysSoundFlag == 1) { audio_incoming_file.Play(); } lock (LANSharingApp.lockerPathSave) { currentPathSave = LANSharingApp.pathSave; } switch (MessageBox.Show(userInfo[0] + " " + userInfo[1] + " " + userInfo[2] + " wants to send you a file: " + fileName, "Incoming File", MessageBoxButtons.OKCancel)) { case DialogResult.Cancel: writer.Write("cancel"); reader.Close(); writer.Close(); client.Close(); return; case DialogResult.OK: writer.Write("ok"); break; default: break; } } else if (LANSharingApp.saveProfile == 2) { // no automatic save, ask where to save if (LANSharingApp.sysSoundFlag == 1) { audio_incoming_file.Play(); } switch (MessageBox.Show(userInfo[0] + " " + userInfo[1] + " " + userInfo[2] + " wants to send you a file: " + fileName, "Incoming File", MessageBoxButtons.OKCancel)) { case DialogResult.Cancel: writer.Write("cancel"); reader.Close(); writer.Close(); client.Close(); return; case DialogResult.OK: //choose path // cause thread are MTA on launch Thread t = new Thread(() => { using (FolderBrowserDialog fbd = new FolderBrowserDialog()) { DialogResult dr = fbd.ShowDialog(); if (dr == DialogResult.OK) { currentPathSave = fbd.SelectedPath; } } }); t.IsBackground = true; // must use STA for the new thread t.SetApartmentState(ApartmentState.STA); t.Start(); t.Join(); if (currentPathSave == null) { writer.Write("cancel"); reader.Close(); writer.Close(); client.Close(); return; } else { writer.Write("ok"); } break; default: break; } //show a message box with browse destination } else { // automatic save lock (LANSharingApp.lockerPathSave) { currentPathSave = LANSharingApp.pathSave; } writer.Write("ok"); } Console.WriteLine("[Server] - Inviato al client decisione: "); // receive file msg = reader.ReadString(); long checkNumber = long.Parse(msg); Console.WriteLine("[Server] - checkNumeber: " + checkNumber); // detect duplicates SaveFileDialog saveFile = new SaveFileDialog(); saveFile.InitialDirectory = currentPathSave; // get a random file name for zip --> no collision saveFile.FileName = Path.GetRandomFileName(); zipFileName = LANSharingApp.tmpPath + "\\" + saveFile.FileName; //add to list LANSharingApp.tempFileRecv.Add(zipFileName); Console.WriteLine("[Server] - salvataggio in: " + saveFile.FileName); using (Stream output = new FileStream(zipFileName, FileMode.Create, FileAccess.ReadWrite, FileShare.Delete)) { // Buffer for reading data Byte[] bytes = new Byte[1024]; int length; check = 0;// check if there are no data, in case of delete of file before sending on Client side Console.WriteLine("[Server] - inizio lettura"); while ((length = networkStream.Read(bytes, 0, bytes.Length)) != 0) { check += length; output.Write(bytes, 0, length); } } Console.WriteLine("[Server] - fine lettura"); Console.WriteLine("[Server] - check:" + check); if (check != checkNumber) //control if something go wrong { File.Delete(zipFileName); MessageFormError mfe = new MessageFormError("Error: missing or corrupted file: " + fileName + "\n" + " from " + userInfo[0] + " " + userInfo[1]); if (LANSharingApp.sysSoundFlag == 1) { audio_error.Play(); } // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfe.Show(); }); } else //extract file from zip { //unzip and delete zip archive Console.WriteLine("[Server] - estrazione di:" + zipFileName); Console.WriteLine("[Server] - estrazione in:" + currentPathSave + "\\" + newName); lock (lockerFile) { newName = GetUniqueNameFile(fileName, currentPathSave); //special function //flag used during unzip process bool duplicate = true; if (fileName.Equals(newName)) { duplicate = false; // no duplicate if the name doesn't change } //at this time i can have or not a duplicate // each time i receive a duplicate, move the original as copie N and save the last one as original if (duplicate) { System.IO.File.Move(currentPathSave + "\\" + fileName, currentPathSave + "\\" + newName); } // Open an existing zip file with random name ZipStorer zip = ZipStorer.Open(zipFileName, FileAccess.Read); // Read the central directory collection List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); foreach (ZipStorer.ZipFileEntry entry in dir) // there is only one entry !!! { zip.ExtractFile(entry, currentPathSave + "\\" + fileName); } zip.Close(); } } } else { //receive folder if (LANSharingApp.saveProfile == 1) { // no automatic save lock (LANSharingApp.lockerPathSave) { currentPathSave = LANSharingApp.pathSave; } if (LANSharingApp.sysSoundFlag == 1) { audio_incoming_file.Play(); } switch (MessageBox.Show(userInfo[0] + " " + userInfo[1] + " " + userInfo[2] + " wants to send you a folder: " + fileName, "Incoming Folder", MessageBoxButtons.OKCancel)) { case DialogResult.Cancel: writer.Write("cancel"); reader.Close(); writer.Close(); client.Close(); return; case DialogResult.OK: writer.Write("ok"); break; default: break; } } else if (LANSharingApp.saveProfile == 2) { // no automatic save, ask where to save audio_incoming_file.Play(); switch (MessageBox.Show(userInfo[0] + " " + userInfo[1] + " " + userInfo[2] + " wants to send you a folder: " + fileName, "Incoming Folder", MessageBoxButtons.OKCancel)) { case DialogResult.Cancel: writer.Write("cancel"); reader.Close(); writer.Close(); client.Close(); return; case DialogResult.OK: //choose path // cause thread are MTA on launch Thread t = new Thread(() => { using (FolderBrowserDialog fbd = new FolderBrowserDialog()) { DialogResult dr = fbd.ShowDialog(); if (dr == DialogResult.OK) { currentPathSave = fbd.SelectedPath; } } }); t.IsBackground = true; // must use STA for the new thread t.SetApartmentState(ApartmentState.STA); t.Start(); t.Join(); if (currentPathSave == null) { writer.Write("cancel"); reader.Close(); writer.Close(); client.Close(); return; } else { writer.Write("ok"); } break; default: break; } //show a message box with browse destination } else { // automatic save lock (LANSharingApp.lockerPathSave) { currentPathSave = LANSharingApp.pathSave; } writer.Write("ok"); } Console.WriteLine("[Server] - Inviato al client decisione "); // receive file msg = reader.ReadString(); long checkNumber = long.Parse(msg); Console.WriteLine("[Server] - checkNumeber: " + checkNumber); // detect duplicates SaveFileDialog saveFile = new SaveFileDialog(); saveFile.InitialDirectory = currentPathSave; string noZip = fileName; string randomName = Path.GetRandomFileName(); //directory zip zipDirName = LANSharingApp.tmpPath + "\\" + randomName; //add dir random to list LANSharingApp.tempFileRecv.Add(zipDirName); saveFile.FileName = randomName; Console.WriteLine("[Server] - salvataggio in: " + saveFile.FileName); using (Stream output = new FileStream(zipDirName, FileMode.Create, FileAccess.ReadWrite, FileShare.Delete)) { // Buffer for reading data Byte[] bytes = new Byte[1024]; int length; check = 0; Console.WriteLine("[Server] - inizio lettura zip"); while ((length = networkStream.Read(bytes, 0, bytes.Length)) != 0) { check += length; output.Write(bytes, 0, length); } } Console.WriteLine("[Server] - fine lettura zip"); Console.WriteLine("[Server] - check: " + check); if (check != checkNumber) //control if something go wrong { File.Delete(zipDirName); MessageFormError mfe = new MessageFormError("Error: missing or corrupted directory: " + fileName + "\n" + " from " + userInfo[0] + " " + userInfo[1]); if (LANSharingApp.sysSoundFlag == 1) { audio_error.Play(); } // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfe.Show(); }); Console.WriteLine("[Server] - chiusa connessione"); return; } else { //unzip and delete zip archive Console.WriteLine("[Server] - estrazione di:" + zipDirName); Console.WriteLine("[Server] - estrazione in:" + currentPathSave + "\\" + newName); lock (lockerDir) { newName = GetUniqueNameDir(noZip, currentPathSave); //special function //flag used during unzip process bool duplicate = true; if (noZip.Equals(newName)) { duplicate = false; // no duplicate if the name doesn't change } //at this time i can have or not a duplicate // each time i receive a duplicate, move the original as copie N and save the last one as original if (duplicate) { Directory.Move(currentPathSave + "\\" + noZip, currentPathSave + "\\" + newName); } ZipFile.ExtractToDirectory(zipDirName, currentPathSave); File.Delete(zipDirName); // delete zip } } } Console.WriteLine("[Server] - chiusa connessione"); } } catch (Exception e) { Console.WriteLine(e.ToString()); LANSharingApp.LogFile(e.Message, e.ToString(), e.Source); MessageFormError mfe = new MessageFormError("An error has occured during FTP process Server Side"); audio_error.Play(); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfe.Show(); }); } finally { if (zipFileName != null && File.Exists(zipFileName)) { File.Delete(zipFileName); LANSharingApp.tempFileRecv.Remove(zipFileName); } if (zipDirName != null && Directory.Exists(zipDirName)) { File.Delete(zipDirName); LANSharingApp.tempFileRecv.Remove(zipDirName); } //release resources if (writer != null) { writer.Close(); } if (reader != null) { reader.Close(); } if (client != null) { client.Close(); } } }
// It is the real server, each time we receive a new request crete a new thread to handle it // use a manualResetEvent to notify when the user is OFFLINE and all servers must stop and reject request public void ReceiveFileProcedure() { TcpListener listener = null; BinaryWriter writer = null; TcpClient client = null; try { listener = new TcpListener(LANSharingApp.umu.getAdmin().getIp(), LANSharingApp.umu.getAdmin().getPort()); // Imposto tcplistener con le credenziali della persona listener.Start(); // Istart listen for incoming TCP connections Console.WriteLine("[Server] - creazione tcp listener: "); int n = 0; // request number, DEBUG purpose while (!LANSharingApp.closing) { LANSharingApp.mre.WaitOne(); //wait on mre, online or launch app Console.WriteLine("[Server] - in ascolto... "); client = listener.AcceptTcpClient(); // blocking if (LANSharingApp.umu.getAdmin().isOnline()) { // create a new thread to satisfy the client request n++; Console.WriteLine("[Server] - accettata richiesta #n: " + n); Thread t = new Thread(ProcessClientRequest); //process the client request t.IsBackground = true; t.Start(client); } else { //cancel client request //avoid block on client side, need to comunicate the decision NetworkStream networkStream = client.GetStream(); writer = new BinaryWriter(networkStream); writer.Write("cancel"); writer.Flush(); } } } catch (Exception e) { Console.WriteLine(e.ToString()); LANSharingApp.LogFile(e.Message, e.ToString(), e.Source); } finally { //release resources if (listener != null) { listener.Stop(); } if (writer != null) { writer.Close(); } if (client != null) { client.Close(); } } }
private void user_tile_Click(object sender, EventArgs e) { try { // search for a user image old_image = LANSharingApp.user_image; int old_flag = LANSharingApp.image_flag; Console.WriteLine("Old Flag: " + old_flag); var t_image = new Thread((ThreadStart)(() => { OpenFileDialog ofd_image = new OpenFileDialog(); ofd_image.Filter = "JPG|*.jpg;*.jpeg|BMP|*.bmp|GIF|*.gif|PNG|*.png|TIFF|*.tif;*.tiff"; ofd_image.Title = "Select a File"; if (ofd_image.ShowDialog() == DialogResult.Cancel) { return; } myPath_image = ofd_image.FileName; Console.WriteLine("Path Immagine: " + myPath_image); })); t_image.IsBackground = true; t_image.SetApartmentState(ApartmentState.STA); // application born as MTA, but i need STA for graphical purpose t_image.Start(); t_image.Join(); Image image; if (myPath_image != null) { path_80 = myPath_image; modified_image = 1; //user image has changed, used clicked "ok" flag_default_image = 1; //image = Image.FromFile(@"" + myPath_image); using (var bmpTemp = new Bitmap(@"" + myPath_image)) { if (Array.IndexOf(bmpTemp.PropertyIdList, 274) > -1) { var orientation = (int)bmpTemp.GetPropertyItem(274).Value[0]; switch (orientation) { case 1: // No rotation required. break; case 2: bmpTemp.RotateFlip(RotateFlipType.RotateNoneFlipX); break; case 3: bmpTemp.RotateFlip(RotateFlipType.Rotate180FlipNone); break; case 4: bmpTemp.RotateFlip(RotateFlipType.Rotate180FlipX); break; case 5: bmpTemp.RotateFlip(RotateFlipType.Rotate90FlipX); break; case 6: bmpTemp.RotateFlip(RotateFlipType.Rotate90FlipNone); break; case 7: bmpTemp.RotateFlip(RotateFlipType.Rotate270FlipX); break; case 8: bmpTemp.RotateFlip(RotateFlipType.Rotate270FlipNone); break; } // This EXIF data is now invalid and should be removed. bmpTemp.RemovePropertyItem(274); } image = new Bitmap(bmpTemp); } image = ScaleImage(image, 80, 80); button2.Visible = true; saveButton.Enabled = true; this.user_tile.TileImage = image; old_image = actual_image; actual_image = image; actual_small_image = ScaleImage(image, 32, 32); Console.WriteLine("Modified: " + modified_image + " Old image: " + old_image + " New Image: " + actual_image); user_tile.Refresh(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); LANSharingApp.LogFile(ex.Message, ex.ToString(), ex.Source); LANSharingApp.closing = true; LANSharingApp.serverThread.Join(); Application.Exit(); } }
private void Save_Click(object sender, EventArgs e) { LANSharingApp.gui.settingsButton.Enabled = true; LANSharingApp.gui.settingsButton.Refresh(); try { count_change_image++; if (flag_default_image == 1) { LANSharingApp.image_flag = 1; } else { LANSharingApp.image_flag = 0; } LANSharingApp.user_image = actual_image; LANSharingApp.gui.user_tile.TileImage = actual_image; LANSharingApp.gui.user_tile.Refresh(); LANSharingApp.user_image_path = path_80; LANSharingApp.user_small_image = actual_small_image; //Console.WriteLine("New path: " + LANSharingApp.user_image_path); LANSharingApp.user_image_path = path_80; LANSharingApp.user_small_image_path = path_32; // save radio button modification if (radioButtonNoAutomaticComplete.Checked) { LANSharingApp.saveProfile = 2; } else if (radioButtonNoAutomaticDefault.Checked) { LANSharingApp.saveProfile = 1; } else { LANSharingApp.saveProfile = 0; } // save new path lock (LANSharingApp.lockerPathSave) { LANSharingApp.pathSave = destinationPath.Text; } // save changes on admin info LANSharingApp.umu.getAdmin().setFirstName(textBoxFirstName.Text); LANSharingApp.umu.getAdmin().setLastName(textBoxLastName.Text); string fn = LANSharingApp.umu.getAdmin().getFirstName(); string ln = LANSharingApp.umu.getAdmin().getLastName(); string[] c = new string[2]; c[0] = fn; c[1] = ln; LANSharingApp.UpdateUserPreference(); // clear operation saveButton.Enabled = false; LANSharingApp.gui.settingsButton.Enabled = true; LANSharingApp.gui.settingsButton.Refresh(); this.Close(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); LANSharingApp.LogFile(ex.Message, ex.ToString(), ex.Source); LANSharingApp.closing = true; LANSharingApp.serverThread.Join(); Application.Exit(); } }
//kernel of protocol Client side private static void FTP_protocol(string ip, string port, string firstNameReceiver, string lastnameReceiver) { Console.WriteLine("[Client] - Inizio invio a " + ip + ":" + port + " nome: " + firstNameReceiver + " cognome: " + lastnameReceiver); byte[] buffer = new byte[1024]; string msg = ""; string msg_progress = ""; byte[] buffer2 = new byte[1024]; TcpClient client = new TcpClient(); BinaryWriter writer = null; BinaryReader reader = null; string zipDir = null; SendFile windowSendFile = null; ZipStorer zipFile = null; string zipFileName = null; if (!Directory.Exists(LANSharingApp.tmpPath)) { Directory.CreateDirectory(LANSharingApp.tmpPath); } try { IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(ip), int.Parse(port)); string type = null; Console.WriteLine("[Client] - tentativo invio a:" + ip + ":" + port + " nome: " + firstNameReceiver + " cognome: " + lastnameReceiver); client.ReceiveBufferSize = 1024; client.SendBufferSize = 1024; Console.WriteLine("[Client] - creato tcp client"); //start connection TCP client.Connect(IPAddress.Parse(ip), int.Parse(port)); Console.WriteLine("[Client] - connesso tcp client"); using (NetworkStream networkStream = client.GetStream()) { writer = new BinaryWriter(networkStream); reader = new BinaryReader(networkStream); // send header to the Server // userFirstName,userLastName, userIP @ type @ path string userFirstName = LANSharingApp.umu.getAdmin().getFirstName(); string userLastName = LANSharingApp.umu.getAdmin().getLastName(); string userIp = LANSharingApp.umu.getAdmin().getIp().ToString(); string myPath = null; string fullPath = null; lock (LANSharingApp.lockerPathSend) { myPath = Path.GetFileName(LANSharingApp.pathSend); fullPath = LANSharingApp.pathSend; } //identify if the admin is sending a file or a directory if ((File.GetAttributes(fullPath) & FileAttributes.Directory) == FileAttributes.Directory) { type = "directory"; } else { type = "file"; } // case file if (type.CompareTo("file") == 0) { // username,usersurname, userip @ type @ path @ checkNumber //msg_progress = nameReceiver + "," + lastnameReceiver + "," + ip + "@" + type + "@" + myPath + "@" + dataToSend.Length; msg = userFirstName + "," + userLastName + "," + userIp + "@" + type + "@" + myPath; writer.Write(msg); Console.WriteLine("[Client] - Inviato al server: " + msg); Console.WriteLine("[Client] - aspetto risposta"); //wait for answer msg = reader.ReadString(); Console.WriteLine("[Client] - risposta ricevuta: " + msg); if (msg.CompareTo("ok") == 0) { //if ok, send file //check file if (!File.Exists(fullPath)) { MessageFormError mfe = new MessageFormError("Error: file deleted"); if (LANSharingApp.sysSoundFlag == 1) { audio_error.Play(); } // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfe.Show(); }); return; } Console.WriteLine("[Client] - inizio invio file "); //zip the file string randomName = LANSharingApp.tmpPath + "\\" + Path.GetRandomFileName(); //add file to list LANSharingApp.tempFileSend.Add(randomName); //specific progress bar for each different user windowSendFile = new SendFile("Progress of ftp file " + myPath + " to " + firstNameReceiver + " " + lastnameReceiver, "Compression in Progress"); windowSendFile.StartPosition = FormStartPosition.CenterScreen; int offset = 0; // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.Show(); } }); zipFileName = randomName; zipFile = ZipStorer.Create(randomName, ""); zipFile.AddFile(ZipStorer.Compression.Store, fullPath, Path.GetFileName(myPath), ""); zipFile.Close(); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.clearCompression(); } }); //some usefull information byte[] dataToSend = File.ReadAllBytes(randomName); msg = dataToSend.Length + ""; writer.Write(msg); int chunk = 1024 * 1024; int n = dataToSend.Length / chunk; int lastChunk = dataToSend.Length - (n * chunk); int i; // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.setMinMaxBar(0, n + 1); } }); for (i = 0; i < n; i++) { if (windowSendFile.cts.IsCancellationRequested) { //manage cancel operation Console.WriteLine("[Client] - invio annullato "); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.Dispose(); windowSendFile.Close(); } }); return; } else { // no cancel networkStream.Write(dataToSend, offset, chunk); networkStream.Flush(); offset += chunk; // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.incrementProgressBar(); } }); } } Thread.Sleep(5000); // give time to user to react if (windowSendFile.cts.IsCancellationRequested) { //manage cancel operation Console.WriteLine("[Client] - invio annullato "); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.Dispose(); windowSendFile.Close(); } }); return; } if (lastChunk != 0) { networkStream.Write(dataToSend, offset, lastChunk); networkStream.Flush(); } // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.incrementProgressBar(); } }); Console.WriteLine("[Client] - fine invio file "); Console.WriteLine("[Client] - close protocol "); } else//cancel { Console.WriteLine("[Client] - close protocol "); MessageFormError mfex = new MessageFormError(firstNameReceiver + " " + lastnameReceiver + " refused file"); if (LANSharingApp.sysSoundFlag == 1) { audio_error.Play(); } // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfex.Show(); }); } Thread.Sleep(1000); // give time to sender to see the final state of progress bar // delegate the operation on form to the GUI --> close the send window if (windowSendFile != null) { LANSharingApp.gui.Invoke((MethodInvoker) delegate() { windowSendFile.Close(); }); } } else //case directory { // username,usersurname, userip @ type @ path msg = userFirstName + "," + userLastName + "," + userIp + "@" + type + "@" + myPath; writer.Write(msg); Console.WriteLine("[Client] - Inviato al server: " + msg); Console.WriteLine("[Client] - aspetto risposta"); //wait answer msg = reader.ReadString(); Console.WriteLine("[Client] - risposta ricevuta: " + msg); if (msg.CompareTo("ok") == 0) { // if ok, send directory if (!Directory.Exists(fullPath)) { MessageFormError mfe = new MessageFormError("Error: directory deleted during send process"); if (LANSharingApp.sysSoundFlag == 1) { audio_error.Play(); } // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfe.Show(); }); return; } //zip directory, better performance on LAN //random name, no collision on creation multiple zip of same file zipDir = LANSharingApp.tmpPath + "\\" + Path.GetRandomFileName(); //add to list LANSharingApp.tempFileSend.Add(zipDir); //specific progress bar for each different user windowSendFile = new SendFile("Progress of ftp directory " + myPath + " to " + firstNameReceiver + " " + lastnameReceiver, " Compression in progress"); windowSendFile.StartPosition = FormStartPosition.CenterScreen; int offset = 0; // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.Show(); } }); ZipFile.CreateFromDirectory(fullPath, zipDir, CompressionLevel.NoCompression, true); Console.WriteLine("[Client] - zip creato:" + zipDir); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.clearCompression(); } }); Console.WriteLine("[Client] - inizio invio directory zip"); byte[] dataToSend = File.ReadAllBytes(zipDir); msg = dataToSend.Length + ""; writer.Write(msg); int chunk = 1024 * 1024; int n = dataToSend.Length / chunk; int lastChunk = dataToSend.Length - (n * chunk); int i; // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.setMinMaxBar(0, n + 1); } }); for (i = 0; i < n; i++) { if (windowSendFile.cts.IsCancellationRequested) { //manage cancel operation Console.WriteLine("[Client] - invio annullato "); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.Dispose(); windowSendFile.Close(); } }); return; } else { // no cancel networkStream.Write(dataToSend, offset, chunk); networkStream.Flush(); offset += chunk; // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.incrementProgressBar(); } }); } } Thread.Sleep(5000); // give time to user to react if (windowSendFile.cts.IsCancellationRequested) { //manage cancel operation Console.WriteLine("[Client] - invio annullato "); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.Dispose(); windowSendFile.Close(); } }); return; } if (lastChunk != 0) { networkStream.Write(dataToSend, offset, lastChunk); networkStream.Flush(); } // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.incrementProgressBar(); } }); Console.WriteLine("[Client] - fine invio directory zip "); //File.Delete(zipDir); Console.WriteLine("[Client] - close protocol "); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.endFTP(); } }); } else // if cancel, close { Console.WriteLine("[Client] - close protocol "); MessageFormError mfex = new MessageFormError(firstNameReceiver + " " + lastnameReceiver + " refused file"); if (LANSharingApp.sysSoundFlag == 1) { audio_error.Play(); } // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfex.Show(); }); } Thread.Sleep(1000); // give time to sender to see the final state of progress bar // delegate the operation on form to the GUI --> close the send window LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.Close(); } }); } Console.WriteLine("[Client] - chiusa connessione"); } } catch (System.IO.IOException cancelException) { Console.WriteLine(cancelException.ToString()); LANSharingApp.LogFile(cancelException.Message, cancelException.ToString(), cancelException.Source); if (LANSharingApp.sysSoundFlag == 1) { audio_error.Play(); } MessageFormError mfe = new MessageFormError("The operation was canceled"); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfe.Show(); if (windowSendFile != null) { windowSendFile.errorFTP(); } }); Thread.Sleep(1000); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfe.Show(); if (windowSendFile != null) { windowSendFile.Dispose(); windowSendFile.Close(); } }); } catch (Exception e) { Console.WriteLine(e.ToString()); LANSharingApp.LogFile(e.Message, e.ToString(), e.Source); if (LANSharingApp.sysSoundFlag == 1) { audio_error.Play(); } MessageFormError mfe = new MessageFormError("The selected user is offline, is not possible to satisfy your request"); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfe.Show(); if (windowSendFile != null) { windowSendFile.errorFTP(); } }); Thread.Sleep(1000); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfe.Show(); if (windowSendFile != null) { windowSendFile.Dispose(); windowSendFile.Close(); } }); } finally { //release resources if (File.Exists(zipFileName)) { File.Delete(zipFileName); LANSharingApp.tempFileSend.Remove(zipFileName); } if (zipDir != null) { File.Delete(zipDir); LANSharingApp.tempFileSend.Remove(zipDir); } if (writer != null) { writer.Close(); } if (reader != null) { reader.Close(); } if (client != null) { client.Close(); } } }