private int PushToNuGetRepository(Execution execution, bool pushGitVersion, string platform, string commitHash) { if (pushGitVersion) { // We have to patch the package file in memory to include the Git hash // as part of the version. This is required so that Protobuild // can resolve source-equivalent binary packages. RedirectableConsole.WriteLine("Patching package file to include Git version information..."); using (var patchedPackage = new MemoryStream()) { using (var patchedPackageWriter = ZipStorer.Create(patchedPackage, string.Empty, true)) { using (var packageReader = ZipStorer.Open(execution.PackagePushFile, FileAccess.Read)) { var entries = packageReader.ReadCentralDir(); var progressRenderer = new PackagePatchProgressRenderer(entries.Count); var i = 0; foreach (var entry in packageReader.ReadCentralDir()) { if (entry.FilenameInZip.EndsWith(".nuspec") && !entry.FilenameInZip.Contains("/")) { // This is the NuGet specification file in the root of the package // that we need to patch. using (var fileStream = new MemoryStream()) { packageReader.ExtractFile(entry, fileStream); fileStream.Seek(0, SeekOrigin.Begin); string nuspecContent; using ( var reader = new StreamReader(fileStream, Encoding.UTF8, true, 4096, true)) { nuspecContent = reader.ReadToEnd(); var regex = new Regex("version\\>[^\\<]+\\<\\/version"); nuspecContent = regex.Replace(nuspecContent, "version>" + NuGetVersionHelper.CreateNuGetPackageVersion(commitHash, platform) + "</version"); using (var patchedFileStream = new MemoryStream()) { using ( var writer = new StreamWriter(patchedFileStream, Encoding.UTF8, 4096, true)) { writer.Write(nuspecContent); writer.Flush(); patchedFileStream.Seek(0, SeekOrigin.Begin); patchedPackageWriter.AddStream( entry.Method, entry.FilenameInZip, patchedFileStream, entry.ModifyTime, entry.Comment, true); } } } } } else { using (var fileStream = new MemoryStream()) { packageReader.ExtractFile(entry, fileStream); fileStream.Seek(0, SeekOrigin.Begin); patchedPackageWriter.AddStream( entry.Method, entry.FilenameInZip, fileStream, entry.ModifyTime, entry.Comment, true); } } i++; progressRenderer.SetProgress(i); } progressRenderer.FinalizeRendering(); } } patchedPackage.Seek(0, SeekOrigin.Begin); // Push the patched package to the NuGet repository. RedirectableConsole.WriteLine("Uploading package with Git version..."); return(this.PushNuGetBinary(execution.PackagePushUrl, execution.PackagePushApiKey, patchedPackage, execution.PackagePushIgnoreOnExisting)); } } else { RedirectableConsole.WriteLine("Uploading package with semantic version..."); using ( var stream = new FileStream(execution.PackagePushFile, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (var memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); // Note about the true argument here: We always ignore a conflict for the semantic version, as // the build server may be pushing on every commit. In this scenario, developers will leave // the semantic version as-is until they're ready to release a new semantic version. return(this.PushNuGetBinary(execution.PackagePushUrl, execution.PackagePushApiKey, memoryStream, true)); } } } }
public override void Produce() { //produce data.zip which offline installer's program needs try { //put required data into /offline folder Util.CreateDirectory(DataFolderDirectory); //data folder will look like this: // \offline\data\PowerPointLabs.vsto // \offline\data\setup.exe // \offline\data\Application Files\PowerPointLabs_A_B_C_D\* File.Copy(DeployConfig.DirVsto, DataFolderDirectory + @"\PowerPointLabs.vsto", TextCollection.Const.IsOverWritten); File.Copy(DeployConfig.DirCurrent + @"\setup.exe", DataFolderDirectory + @"\setup.exe", TextCollection.Const.IsOverWritten); var applicationFilesDirectory = DataFolderDirectory + @"\Application Files"; var buildNameDirectory = DataFolderDirectory + @"\Application Files\" + Config.DirBuildName; Util.CreateDirectory(applicationFilesDirectory); Util.CreateDirectory(buildNameDirectory); Util.CopyFolder(Config.DirBuild, buildNameDirectory, TextCollection.Const.IsOverWritten); //make data folder into a zip file, named data.zip // \offline\data.zip var dataZipPath = DeployConfig.DirOfflineInstallerFolder + @"\data.zip"; //remove the old zip file, if any if (File.Exists(dataZipPath)) { File.Delete(dataZipPath); } ZipFile.CreateFromDirectory(DataFolderDirectory, dataZipPath); //remove data folder Directory.Delete(DataFolderDirectory, TextCollection.Const.IsSubDirectoryToDelete); } catch (Exception e) { Util.DisplayWarning(TextCollection.Const.ErrorZipFilesMissing, e); } //pack all // \offline\data.zip // \offline\setup.exe (offline installer program) //into this // \offline\PowerPointLabsInstaller.exe (package, to be sent to user) RunIExpress(DeployConfig.DirOfflineInstallerFolder); //Turn IExpress package exe to zip if (File.Exists(DeployConfig.DirOfflineInstallerFolder + @"\PowerPointLabsInstaller.exe")) { var installerZip = ZipStorer.Create(DeployConfig.DirOfflineInstallerFolder + @"\PowerPointLabsInstaller.zip", "PowerPointLabs Offline Installer"); installerZip.AddFile(ZipStorer.Compression.Store, DeployConfig.DirOfflineInstallerFolder + @"\PowerPointLabsInstaller.exe" , "setup.exe" , ""); installerZip.Close(); } else { Util.DisplayWarning("IExpress package fails to produce", new FileNotFoundException()); } }
private void CreateReportZip(SerializableException serializableException, Report report) { // Test if it has NOT been more than x many days since entry assembly was last modified) if (Settings.StopReportingAfter < 0 || File.GetLastWriteTime(Settings.EntryAssembly.Location).AddDays(Settings.StopReportingAfter).CompareTo(DateTime.Now) > 0) { // Test if there is already more than enough queued report files if (Settings.MaxQueuedReports < 0 || Storer.GetReportCount() < Settings.MaxQueuedReports) { var reportFileName = "Exception_" + DateTime.UtcNow.ToFileTime() + ".zip"; var minidumpFilePath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Exception_MiniDump_" + DateTime.UtcNow.ToFileTime() + ".mdmp"); using (var storer = new Storer()) using (var zipStorer = ZipStorer.Create(storer.CreateReportFile(reportFileName), string.Empty)) using (var stream = new MemoryStream()) { // Store the exception var serializer = new XmlSerializer(typeof(SerializableException)); serializer.Serialize(stream, serializableException); stream.Position = 0; zipStorer.AddStream(ZipStorer.Compression.Deflate, StoredItemFile.Exception, stream, DateTime.UtcNow, string.Empty); // Store the report stream.SetLength(0); try { serializer = report.CustomInfo != null ? new XmlSerializer(typeof(Report), new[] { report.CustomInfo.GetType() }) : new XmlSerializer(typeof(Report)); serializer.Serialize(stream, report); } catch (Exception exception) { Logger.Error( string.Format( "The given custom info of type [{0}] cannot be serialized. Make sure that given type and inner types are XML serializable.", report.CustomInfo.GetType()), exception); report.CustomInfo = null; serializer = new XmlSerializer(typeof(Report)); serializer.Serialize(stream, report); } stream.Position = 0; zipStorer.AddStream(ZipStorer.Compression.Deflate, StoredItemFile.Report, stream, DateTime.UtcNow, string.Empty); // Add the memory minidump to the report file (only if configured so) if (DumpWriter.Write(minidumpFilePath)) { zipStorer.AddFile(ZipStorer.Compression.Deflate, minidumpFilePath, StoredItemFile.MiniDump, string.Empty); File.Delete(minidumpFilePath); } // Add any user supplied files in the report (if any) if (Settings.AdditionalReportFiles.Count != 0) { // ToDo: This needs a lot more work! this.AddAdditionalFiles(zipStorer); } } Logger.Trace("Created a new report file. Currently the number of report files queued to be send is: " + Storer.GetReportCount()); } else { Logger.Trace( "Current report count is at its limit as per 'Settings.MaxQueuedReports (" + Settings.MaxQueuedReports + ")' setting: Skipping bug report generation."); } } else { Logger.Trace( "As per setting 'Settings.StopReportingAfter(" + Settings.StopReportingAfter + ")', bug reporting feature was enabled for a certain amount of time which has now expired: Bug reporting is now disabled."); // ToDo: Completely eliminate this with SettingsOverride.DisableReporting = true; since enumerating filesystem adds overhead); if (Storer.GetReportCount() > 0) { Logger.Trace( "As per setting 'Settings.StopReportingAfter(" + Settings.StopReportingAfter + ")', bug reporting feature was enabled for a certain amount of time which has now expired: Truncating all expired bug reports."); Storer.TruncateReportFiles(0); } } }
/// <summary> /// Builds the specified config. /// </summary> /// <param name="config">The build config to use.</param> public static void Build(BuildConfig config) { if (!IsTargetSupported(config.target)) { Debug.LogError(string.Format( "Failed to build {0}; {0} build module is not installed", config.target )); return; } // Do the build var path = Path.Combine(GetBuildPath(), config.folder); var options = new BuildPlayerOptions(); options.target = config.target; options.scenes = EditorBuildSettings.scenes.Select(x => x.path).ToArray(); switch (config.target) { // The WebGL build treats the locationPathName as the folder the // build will be generated in instead of the name of the // executable, which will always be index.html case BuildTarget.WebGL: options.locationPathName = path; break; default: options.locationPathName = Path.Combine(path, GetExeFilename(config.exeName, config.target)); break; } try { if (Directory.Exists(path)) { Directory.Delete(path, true); } BuildPipeline.BuildPlayer(options); } catch (Exception e) { Debug.LogError(string.Format( "Failed to build {0}; {1}", config.folder, e)); return; } // Compress the build try { switch (config.target) { // Instead of zipping the entire folder, zip each item in // the folder instead for the Web build. This is because // itch.io expects the index.html file to be in the root // directory of the zipped build. case BuildTarget.WebGL: var zipFilename = path + ".zip"; if (File.Exists(zipFilename)) { File.Delete(zipFilename); } using (var zip = ZipStorer.Create(zipFilename)) { var directories = Directory.GetDirectories(path); foreach (var directory in directories) { zip.AddDirectory( ZipStorer.Compression.Deflate, directory, "" ); } var files = Directory.GetFiles(path); foreach (var file in files) { zip.AddFile( ZipStorer.Compression.Deflate, file, Path.GetFileName(file) ); } } break; case BuildTarget.StandaloneWindows: case BuildTarget.StandaloneWindows64: var zf = path + ".zip"; if (File.Exists(zf)) { File.Delete(zf); } using (var zip = ZipStorer.Create(zf)) { zip.AddDirectory( ZipStorer.Compression.Deflate, path, "" ); } break; default: var archivePath = path + ".tar.gz"; if (File.Exists(archivePath)) { File.Delete(archivePath); } using (var stream = new GZipOutputStream(File.Create(archivePath))) { using (var archive = TarArchive.CreateOutputTarArchive(stream, TarBuffer.DefaultBlockFactor)) { TarCompress(new DirectoryInfo(path), archive); } } break; } } catch (Exception e) { Debug.LogError(string.Format( "Failed to zip {0}; {1}", config.folder, e)); return; } }
public RuntimeChecker(ServerType type, string username) { this.type = type; this.username = username; try { FileManagement fm2 = new FileManagement(); fm2.createFolder(1, username, getGame, null); FileManagement fm3 = new FileManagement(); fm3.createFolder(2, username, getGame, getMatchID); getTimeZip = TextHandling.GetUnixTimestamp(); } catch (Exception) { // we assume that the server is down. Environment.Exit(0); } if (!Directory.Exists(Core.AppPath + "acscreens")) { Directory.CreateDirectory(Core.AppPath + "acscreens"); } ZipStorer zip; zip = ZipStorer.Create(Core.AppPath + "acscreens\\log_" + getMatchID + "_" + getGame + "_" + getTimeZip + ".zip", "ESA AntiCheat log for match " + getMatchID.ToString()); zip.Close(); _fs = new FileStream(Core.AppPath + "acscreens\\log_" + getMatchID + "_" + getGame + "_" + getTimeZip + ".zip", FileMode.Open, FileAccess.ReadWrite, FileShare.None); TaskManagerIsRunning(); ProcessManagement.TriggerTaskmanager(false); writePreGameProcesses(); FileManagement fm4 = new FileManagement(); fm4.postFile(username, getGame, getMatchID, Core.AppPath + "ac_logbeforegame_" + getTimepre + "_matchid" + getMatchID + ".txt"); File.Delete(Core.AppPath + "ac_logbeforegame_" + getTimepre + "_matchid" + getMatchID + ".txt"); using (ScreenshotDump screenpre = new ScreenshotDump()) { try { AeroControl ac = new AeroControl(); ac.ControlAero(false); screenpre.SaveToFile(Core.AppPath + "acscreens\\" + "screen_beforegame_" + getTimepre + "_matchid" + getMatchID + ".jpeg"); fm4.postFile(username, getGame, getMatchID, Core.AppPath + "acscreens\\" + "screen_beforegame_" + getTimepre + "_matchid" + getMatchID + ".jpeg"); File.Delete(Core.AppPath + "acscreens\\" + "screen_beforegame_" + getTimepre + "_matchid" + getMatchID + ".jpeg"); } catch (Exception) { File.WriteAllText(Core.AppPath + "acscreens\\captureerror_" + getTimepre + "_matchid" + getMatchID + ".txt", "Failed to grab screenshot! at " + DateTime.Now.TimeOfDay); FileManagement fm = new FileManagement(); fm.postFile(username, getGame, getMatchID, Core.AppPath + "acscreens\\captureerror_" + getTimepre + "_matchid" + getMatchID + ".txt"); File.Delete(Core.AppPath + "acscreens\\captureerror_" + getTimepre + "_matchid" + getMatchID + ".txt"); ReportForm ef = new ReportForm(); ef.label2.Text = "Screenshot capture failed!"; ef.Show(); } } //---timer--- this.timer = new Timer() { AutoReset = true, Interval = 60000, Enabled = true }; timer.Elapsed += tick; timer.Start(); this.watcher = new ProcessWatchDog(1000); this.watcher.OnNewProcess += new NewProcessStartedEvent(watcher_OnNewProcess); this.gamerunningtimer = new Timer() { AutoReset = true, Interval = 5000, Enabled = true }; gamerunningtimer.Elapsed += gametick; gamerunningtimer.Start(); LaunchGame(); }
void bg_DoWork(object sender, DoWorkEventArgs e) { MapInfo info = (MapInfo)e.Argument; if (!info.Area.IsEmpty) { string bigImage = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + Path.DirectorySeparatorChar + "GMap at zoom " + info.Zoom + " - " + info.Type + "-" + DateTime.Now.Ticks + ".jpg"; e.Result = bigImage; // current area GPoint topLeftPx = info.Type.Projection.FromLatLngToPixel(info.Area.LocationTopLeft, info.Zoom); GPoint rightButtomPx = info.Type.Projection.FromLatLngToPixel(info.Area.Bottom, info.Area.Right, info.Zoom); GPoint pxDelta = new GPoint(rightButtomPx.X - topLeftPx.X, rightButtomPx.Y - topLeftPx.Y); GMap.NET.GSize maxOfTiles = info.Type.Projection.GetTileMatrixMaxXY(info.Zoom); int padding = info.MakeWorldFile || info.MakeKmz ? 0 : 22; { using (Bitmap bmpDestination = new Bitmap((int)(pxDelta.X + padding * 2), (int)(pxDelta.Y + padding * 2))) { using (Graphics gfx = Graphics.FromImage(bmpDestination)) { gfx.InterpolationMode = InterpolationMode.HighQualityBicubic; gfx.SmoothingMode = SmoothingMode.HighQuality; int i = 0; // get tiles & combine into one lock (tileArea) { foreach (var p in tileArea) { if (bg.CancellationPending) { e.Cancel = true; return; } int pc = (int)(((double)++i / tileArea.Count) * 100); bg.ReportProgress(pc, p); foreach (var tp in info.Type.Overlays) { Exception ex; GMapImage tile; // tile number inversion(BottomLeft -> TopLeft) for pergo maps if (tp.InvertedAxisY) { tile = GMaps.Instance.GetImageFrom(tp, new GPoint(p.X, maxOfTiles.Height - p.Y), info.Zoom, out ex) as GMapImage; } else // ok { tile = GMaps.Instance.GetImageFrom(tp, p, info.Zoom, out ex) as GMapImage; } if (tile != null) { using (tile) { long x = p.X * info.Type.Projection.TileSize.Width - topLeftPx.X + padding; long y = p.Y * info.Type.Projection.TileSize.Width - topLeftPx.Y + padding; { gfx.DrawImage(tile.Img, x, y, info.Type.Projection.TileSize.Width, info.Type.Projection.TileSize.Height); } } } } } } // draw routes { foreach (GMapRoute r in Main.routes.Routes) { if (r.IsVisible) { using (GraphicsPath rp = new GraphicsPath()) { for (int j = 0; j < r.Points.Count; j++) { var pr = r.Points[j]; GPoint px = info.Type.Projection.FromLatLngToPixel(pr.Lat, pr.Lng, info.Zoom); px.Offset(padding, padding); px.Offset(-topLeftPx.X, -topLeftPx.Y); GPoint p2 = px; if (j == 0) { rp.AddLine(p2.X, p2.Y, p2.X, p2.Y); } else { System.Drawing.PointF p = rp.GetLastPoint(); rp.AddLine(p.X, p.Y, p2.X, p2.Y); } } if (rp.PointCount > 0) { gfx.DrawPath(r.Stroke, rp); } } } } } // draw polygons { foreach (GMapPolygon r in Main.polygons.Polygons) { if (r.IsVisible) { using (GraphicsPath rp = new GraphicsPath()) { for (int j = 0; j < r.Points.Count; j++) { var pr = r.Points[j]; GPoint px = info.Type.Projection.FromLatLngToPixel(pr.Lat, pr.Lng, info.Zoom); px.Offset(padding, padding); px.Offset(-topLeftPx.X, -topLeftPx.Y); GPoint p2 = px; if (j == 0) { rp.AddLine(p2.X, p2.Y, p2.X, p2.Y); } else { System.Drawing.PointF p = rp.GetLastPoint(); rp.AddLine(p.X, p.Y, p2.X, p2.Y); } } if (rp.PointCount > 0) { rp.CloseFigure(); gfx.FillPath(r.Fill, rp); gfx.DrawPath(r.Stroke, rp); } } } } } // draw markers { foreach (GMapMarker r in Main.objects.Markers) { if (r.IsVisible) { var pr = r.Position; GPoint px = info.Type.Projection.FromLatLngToPixel(pr.Lat, pr.Lng, info.Zoom); px.Offset(padding, padding); px.Offset(-topLeftPx.X, -topLeftPx.Y); px.Offset(r.Offset.X, r.Offset.Y); gfx.ResetTransform(); gfx.TranslateTransform(-r.LocalPosition.X, -r.LocalPosition.Y); gfx.TranslateTransform((int)px.X, (int)px.Y); r.OnRender(gfx); } } // tooltips above foreach (GMapMarker m in Main.objects.Markers) { if (m.IsVisible && m.ToolTip != null && m.IsVisible) { if (!string.IsNullOrEmpty(m.ToolTipText)) { var pr = m.Position; GPoint px = info.Type.Projection.FromLatLngToPixel(pr.Lat, pr.Lng, info.Zoom); px.Offset(padding, padding); px.Offset(-topLeftPx.X, -topLeftPx.Y); px.Offset(m.Offset.X, m.Offset.Y); gfx.ResetTransform(); gfx.TranslateTransform(-m.LocalPosition.X, -m.LocalPosition.Y); gfx.TranslateTransform((int)px.X, (int)px.Y); m.ToolTip.OnRender(gfx); } } } gfx.ResetTransform(); } // draw info if (!info.MakeWorldFile) { System.Drawing.Rectangle rect = new System.Drawing.Rectangle(); { rect.Location = new System.Drawing.Point(padding, padding); rect.Size = new System.Drawing.Size((int)pxDelta.X, (int)pxDelta.Y); } using (Font f = new Font(FontFamily.GenericSansSerif, 9, FontStyle.Bold)) { // draw bounds & coordinates using (Pen p = new Pen(Brushes.DimGray, 3)) { p.DashStyle = System.Drawing.Drawing2D.DashStyle.DashDot; gfx.DrawRectangle(p, rect); string topleft = info.Area.LocationTopLeft.ToString(); SizeF s = gfx.MeasureString(topleft, f); gfx.DrawString(topleft, f, p.Brush, rect.X + s.Height / 2, rect.Y + s.Height / 2); string rightBottom = new PointLatLng(info.Area.Bottom, info.Area.Right).ToString(); SizeF s2 = gfx.MeasureString(rightBottom, f); gfx.DrawString(rightBottom, f, p.Brush, rect.Right - s2.Width - s2.Height / 2, rect.Bottom - s2.Height - s2.Height / 2); } // draw scale using (Pen p = new Pen(Brushes.Blue, 1)) { double rez = info.Type.Projection.GetGroundResolution(info.Zoom, info.Area.Bottom); int px100 = (int)(100.0 / rez); // 100 meters int px1000 = (int)(1000.0 / rez); // 1km gfx.DrawRectangle(p, rect.X + 10, rect.Bottom - 20, px1000, 10); gfx.DrawRectangle(p, rect.X + 10, rect.Bottom - 20, px100, 10); string leftBottom = "scale: 100m | 1Km"; SizeF s = gfx.MeasureString(leftBottom, f); gfx.DrawString(leftBottom, f, p.Brush, rect.X + 10, rect.Bottom - s.Height - 20); } } } } bmpDestination.Save(bigImage, ImageFormat.Jpeg); } } //The worldfile for the original image is: //0.000067897543 // the horizontal size of a pixel in coordinate units (longitude degrees in this case); //0.0000000 //0.0000000 //-0.0000554613012 // the comparable vertical pixel size in latitude degrees, negative because latitude decreases as you go from top to bottom in the image. //-111.743323868834 // longitude of the pixel in the upper-left-hand corner. //35.1254392635083 // latitude of the pixel in the upper-left-hand corner. // generate world file if (info.MakeWorldFile) { string wf = bigImage + "w"; using (StreamWriter world = File.CreateText(wf)) { world.WriteLine("{0:0.000000000000}", (info.Area.WidthLng / pxDelta.X)); world.WriteLine("0.0000000"); world.WriteLine("0.0000000"); world.WriteLine("{0:0.000000000000}", (-info.Area.HeightLat / pxDelta.Y)); world.WriteLine("{0:0.000000000000}", info.Area.Left); world.WriteLine("{0:0.000000000000}", info.Area.Top); world.Close(); } } if (info.MakeKmz) { var kmzFile = Path.GetDirectoryName(bigImage) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(bigImage) + ".kmz"; e.Result = kmzFile; using (ZipStorer zip = ZipStorer.Create(kmzFile, "GMap.NET")) { zip.AddFile(ZipStorer.Compression.Store, bigImage, "files/map.jpg", "map"); using (var readme = new MemoryStream( Encoding.UTF8.GetBytes( string.Format(CultureInfo.InvariantCulture, @"<?xml version=""1.0"" encoding=""UTF-8""?> <kml xmlns=""http://www.opengis.net/kml/2.2"" xmlns:gx=""http://www.google.com/kml/ext/2.2"" xmlns:kml=""http://www.opengis.net/kml/2.2"" xmlns:atom=""http://www.w3.org/2005/Atom""> <GroundOverlay> <name>{8}</name> <LookAt> <longitude>{6}</longitude> <latitude>{7}</latitude> <altitude>0</altitude> <heading>0</heading> <tilt>0</tilt> <range>69327.55500845652</range> </LookAt> <color>91ffffff</color> <Icon> <href>files/map.jpg</href> </Icon> <gx:LatLonQuad> <coordinates> {0},{1},0 {2},{3},0 {4},{5},0 {6},{7},0 </coordinates> </gx:LatLonQuad> </GroundOverlay> </kml>", info.Area.Left, info.Area.Bottom, info.Area.Right, info.Area.Bottom, info.Area.Right, info.Area.Top, info.Area.Left, info.Area.Top, kmzFile)))) { zip.AddStream(ZipStorer.Compression.Store, "doc.kml", readme, DateTime.Now, "kml"); zip.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(); } } }