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(); } }
private void refresh_Click(object sender, EventArgs e) { //call the method to update the list of Online Users this.Timer_Tick_Tock(sender, e); MessageFormError mfe = new MessageFormError("Online users list has been refreshed"); mfe.ShowDialog(); }
public static void UpdateUserPreference() { try { StreamWriter pref; if (File.Exists(Application.StartupPath + @"\\userPreferences.txt")) { File.Delete(Application.StartupPath + @"\\userPreferences.txt"); } pref = new StreamWriter(Application.StartupPath + @"\\userPreferences.txt"); // Write to the file: pref.WriteLine("image_flag " + image_flag); pref.WriteLine("user_image_path " + user_image_path); pref.WriteLine("user_small_image_path " + user_small_image_path); pref.WriteLine("sys_Sound_Flag " + sysSoundFlag); pref.WriteLine("save_profile " + saveProfile); lock (lockerPathSave) { pref.WriteLine("path_save " + pathSave); } // Close the stream: pref.Close(); } catch (Exception e) { Console.WriteLine(e.Message); LogFile(e.Message, e.ToString(), e.Source); if (LANSharingApp.sysSoundFlag == 1) { audio_error.Play(); } // delegate the operation on form to the GUI MessageFormError mfe = new MessageFormError("An exception has occurred in updating userPreference file"); LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfe.ShowDialog(); }); closing = true; LANSharingApp.serverThread.Join(); clearTempFiles(); flushTmpDirectory(); Application.Exit(); } }
// 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(); } }
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 static string[] readUserPreference() { try { StreamReader sr; sr = new StreamReader(Application.StartupPath + @"\\userPreferences.txt"); string[] s = new string[6]; string line; int i = 0; while ((line = sr.ReadLine()) != null) { string[] pref = line.Split(' '); s[i] = pref[1]; i++; } sr.Close(); return(s); } catch (Exception e) { Console.WriteLine(e.Message); LogFile(e.Message, e.ToString(), e.Source); if (LANSharingApp.sysSoundFlag == 1) { audio_error.Play(); } // delegate the operation on form to the GUI MessageFormError mfe = new MessageFormError("An exception has occurred in reading userPreference file"); LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfe.ShowDialog(); }); closing = true; LANSharingApp.serverThread.Join(); clearTempFiles(); flushTmpDirectory(); Application.Exit(); return(null); } }
static void Main(string[] args) { if (!Directory.Exists(tmpPath)) { Directory.CreateDirectory(tmpPath); } //check if the app is already running running = Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Length > 1; //Console.WriteLine("ALready running? " + running); if (running) { string selected = null; if (args.Length == 1) //apertura da context menu { selected = args[0]; lock (LANSharingApp.lockerPathSend) { pathSend = selected; } } // open the memory-mapped MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("myMappedFile"); // declare accessor to write on file MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor(); if (selected != null) { //write in the file: Length|Path //4 offset cause length is on 32 bit byte[] Buffer = ASCIIEncoding.ASCII.GetBytes(selected); accessor.Write(0, Buffer.Length); accessor.Flush(); accessor.WriteArray(4, Buffer, 0, Buffer.Length); accessor.Flush(); //write path in the memory mapped file } else { //write in the file: Lenght|Path accessor.Write(0, 0); } //MessageBox.Show("Application already running in background!!!"); closing = false; } else { if (!closing)// there are no process active { // create a memory-mapped file of length 1000 bytes and give it a 'map name' of 'test' MemoryMappedFile mmf = MemoryMappedFile.CreateNew("myMappedFile", 1000); string selected = null; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (args.Length == 1) //apertura da context menu { selected = args[0]; lock (lockerPathSend) { pathSend = selected; } } //manage user preference if (File.Exists(Application.StartupPath + @"\\userPreferences.txt")) { //userPref already exists --> load old user Pref try { string[] s = new string[6]; s = readUserPreference(); if (s[0].Equals("0")) { //default user image is used LANSharingApp.user_image = global::LANSharing.Properties.Resources.user_80; LANSharingApp.user_small_image = global::LANSharing.Properties.Resources.user_32; LANSharingApp.image_flag = 0; LANSharingApp.user_image_path = "no"; LANSharingApp.user_small_image_path = "no"; Console.WriteLine("Default Image"); } else { //LANSharingApp.user_image = Image.FromFile(s[1]); using (var bmpTemp = new Bitmap(s[1])) { LANSharingApp.user_image = new Bitmap(bmpTemp); } //LANSharingApp.user_small_image = Image.FromFile(s[2]); using (var bmpTemp = new Bitmap(s[2])) { LANSharingApp.user_small_image = new Bitmap(bmpTemp); } LANSharingApp.image_flag = 1; LANSharingApp.user_image_path = s[1]; LANSharingApp.user_small_image_path = s[2]; //custom user image is used Console.WriteLine("Custom Image"); } if (s[3].Equals("1")) { //sound on LANSharingApp.sysSoundFlag = 1; Console.WriteLine("Sound on"); } else { //sound off LANSharingApp.sysSoundFlag = 0; Console.WriteLine("Sound Off"); } int savePref = int.Parse(s[4]); saveProfile = savePref; Console.WriteLine("Save pref: " + saveProfile); lock (lockerPathSave) { LANSharingApp.pathSave = s[5]; } Console.WriteLine("Path pref: " + pathSave); } catch (Exception e) { // Let the user know what went wrong. MessageFormError mfe = new MessageFormError("It's not possible to resume userPreferences: default settings are used"); mfe.ShowDialog(); Console.WriteLine("The userPreference file could not be read"); Console.WriteLine(e.Message); LogFile(e.Message, e.ToString(), e.Source); //default user image is used UpdateUserPreference(); LANSharingApp.user_image = global::LANSharing.Properties.Resources.user_80; LANSharingApp.user_small_image = global::LANSharing.Properties.Resources.user_32; LANSharingApp.image_flag = 0; LANSharingApp.user_image_path = "no"; LANSharingApp.user_small_image_path = "no"; } } else { //write default preference WriteUserPreference(); } // Console.WriteLine("ALready running: opening " + pathSend); // Application.EnableVisualStyles(); // Application.SetCompatibleTextRenderingDefault(false); //create userManagerUnit umu = new UserManagerUnit(); //create a ManualResetEvent used from Server's Threads // true -> server start work || false -> server stop work mre = new ManualResetEvent(true); // create Server istance // active server server = new Server(); serverThread = new Thread(server.EntryPoint) { Name = "serverThread" }; serverThread.IsBackground = true; serverThread.Start(); //create new client client = new Client(); // create gui istance gui = new GUI(selected); //run application Application.Run(gui); } } }
// 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(); } } }
//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(); } } }