Ejemplo n.º 1
0
        private void DownloadKML()
        {
            if (Reachability.InternetConnectionStatus() == NetworkStatus.NotReachable)
            {
                return;
            }

            var client = new WebClient();

            client.DownloadDataCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    return;
                }

                try
                {
                    var localKMZ = Utils.md5(_Mappa.Url) + ".zip";
                    var localKML = Utils.md5(_Mappa.Url) + ".kml";
                    var bytes    = e.Result;
                    var tmpPath  = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

                    File.WriteAllBytes(Path.Combine(tmpPath, localKMZ), bytes);

                    FileStream fs = File.OpenRead(Path.Combine(tmpPath, localKMZ));
                    ZipFile    zf = new ZipFile(fs);

                    foreach (ZipEntry zipEntry in zf)
                    {
                        if (zipEntry.IsFile && zipEntry.Name.Contains(".kml"))
                        {
                            using (FileStream streamWriter = File.Create(Path.Combine(tmpPath, localKML)))
                            {
                                byte[] buffer    = new byte[8192];
                                Stream zipStream = zf.GetInputStream(zipEntry);
                                StreamUtils.Copy(zipStream, streamWriter, buffer);
                            }

                            break;
                        }
                    }

                    if (File.Exists(Path.Combine(tmpPath, localKML)))
                    {
                        _XDoc = XDocument.Load(Path.Combine(tmpPath, localKML));

                        RunOnUiThread(() => {
                            LoadPlacemarks();

                            File.Delete(Path.Combine(tmpPath, localKMZ));
                            File.Delete(Path.Combine(tmpPath, localKML));
                        });
                    }

                    RunOnUiThread(() => HideLoadingOverlay());
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);

                    RunOnUiThread(() => HideLoadingOverlay());
                }
            };

            client.DownloadDataAsync(new Uri(_Mappa.Url));
        }
Ejemplo n.º 2
0
        public static void ScanAccel()
        {
            string[] files = Directory.GetFiles(MainV2.LogDir, "*.tlog", SearchOption.AllDirectories);

            List <string> badfiles = new List <string>();

            foreach (var file in files)
            {
                bool board = false;

                Console.WriteLine(file);

                MAVLinkInterface mavi = new MAVLinkInterface();
                using (mavi.logplaybackfile = new BinaryReader(File.OpenRead(file)))
                {
                    mavi.logreadmode = true;

                    try
                    {
                        while (mavi.logplaybackfile.BaseStream.Position < mavi.logplaybackfile.BaseStream.Length)
                        {
                            byte[] packet = mavi.readPacket();

                            if (packet.Length == 0)
                            {
                                break;
                            }

                            var objectds = mavi.DebugPacket(packet, false);

                            if (objectds is MAVLink.mavlink_param_value_t)
                            {
                                MAVLink.mavlink_param_value_t param = (MAVLink.mavlink_param_value_t)objectds;

                                if (ASCIIEncoding.ASCII.GetString(param.param_id).Contains("INS_PRODUCT_ID"))
                                {
                                    if (param.param_value == 0 || param.param_value == 5)
                                    {
                                        board = true;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }

                            if (objectds is MAVLink.mavlink_raw_imu_t)
                            {
                                MAVLink.mavlink_raw_imu_t rawimu = (MAVLink.mavlink_raw_imu_t)objectds;

                                if (board && Math.Abs(rawimu.xacc) > 2000 && Math.Abs(rawimu.yacc) > 2000 && Math.Abs(rawimu.zacc) > 2000)
                                {
                                    //CustomMessageBox.Show("Bad Log " + file);
                                    badfiles.Add(file);
                                    break;
                                }
                            }
                        }
                    }
                    catch { }
                }
            }

            if (badfiles.Count > 0)
            {
                FileStream      fs        = File.Open(MainV2.LogDir + Path.DirectorySeparatorChar + "SearchResults.zip", FileMode.Create);
                ZipOutputStream zipStream = new ZipOutputStream(fs);
                zipStream.SetLevel(9);             //0-9, 9 being the highest level of compression
                zipStream.UseZip64 = UseZip64.Off; // older zipfile


                foreach (var file in badfiles)
                {
                    // entry 2
                    string   entryName = ZipEntry.CleanName(Path.GetFileName(file)); // Removes drive from name and fixes slash direction
                    ZipEntry newEntry  = new ZipEntry(entryName);
                    newEntry.DateTime = DateTime.Now;

                    zipStream.PutNextEntry(newEntry);

                    // Zip the file in buffered chunks
                    // the "using" will close the stream even if an exception occurs
                    byte[] buffer = new byte[4096];
                    using (FileStream streamReader = File.OpenRead(file))
                    {
                        StreamUtils.Copy(streamReader, zipStream, buffer);
                    }
                    zipStream.CloseEntry();
                }

                zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream
                zipStream.Close();

                CustomMessageBox.Show("Added " + badfiles.Count + " logs to " + MainV2.LogDir + Path.DirectorySeparatorChar + "SearchResults.zip\n Please send this file to Craig Elder <*****@*****.**>");
            }
            else
            {
                CustomMessageBox.Show("No Bad Logs Found");
            }
        }
Ejemplo n.º 3
0
        public void writeKML(string filename)
        {
            try
            {
                writeGPX(filename);

                writeRinex(filename);
            }
            catch { }

            Color[] colours = { Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Blue, Color.Indigo, Color.Violet, Color.Pink };

            AltitudeMode altmode = AltitudeMode.absolute;

            KMLRoot kml  = new KMLRoot();
            Folder  fldr = new Folder("Log");

            Style style = new Style();

            style.Id = "yellowLineGreenPoly";
            style.Add(new LineStyle(HexStringToColor("7f00ffff"), 4));

            Style style1 = new Style();

            style1.Id = "spray";
            style1.Add(new LineStyle(HexStringToColor("4c0000ff"), 0));
            style1.Add(new PolyStyle()
            {
                Color = HexStringToColor("4c0000ff")
            });

            PolyStyle pstyle = new PolyStyle();

            pstyle.Color = HexStringToColor("7f00ff00");
            style.Add(pstyle);

            kml.Document.AddStyle(style);
            kml.Document.AddStyle(style1);

            int stylecode = 0xff;
            int g         = -1;

            foreach (List <Point3D> poslist in position)
            {
                g++;
                if (poslist == null)
                {
                    continue;
                }

                /*
                 * List<PointLatLngAlt> pllalist = new List<PointLatLngAlt>();
                 *
                 * foreach (var point in poslist)
                 * {
                 *  pllalist.Add(new PointLatLngAlt(point.Y, point.X, point.Z, ""));
                 * }
                 *
                 * var ans = Utilities.LineOffset.GetPolygon(pllalist, 2);
                 *
                 *
                 *
                 * while (ans.Count > 0)
                 * {
                 *  var first = ans[0];
                 *  var second = ans[1];
                 *  var secondlast = ans[ans.Count - 2];
                 *  var last = ans[ans.Count-1];
                 *
                 *  ans.Remove(first);
                 *  ans.Remove(last);
                 *
                 *  var polycoords = new BoundaryIs();
                 *
                 *  polycoords.LinearRing = new LinearRing();
                 *
                 *  polycoords.LinearRing.Coordinates.Add(new Point3D(first.Lng, first.Lat, 1));
                 *  polycoords.LinearRing.Coordinates.Add(new Point3D(second.Lng, second.Lat, 1));
                 *  polycoords.LinearRing.Coordinates.Add(new Point3D(secondlast.Lng, secondlast.Lat, 1));
                 *  polycoords.LinearRing.Coordinates.Add(new Point3D(last.Lng, last.Lat, 1));
                 *  polycoords.LinearRing.Coordinates.Add(new Point3D(first.Lng, first.Lat, 1));
                 *
                 *  //if (!IsClockwise(polycoords.LinearRing.Coordinates))
                 *    //  polycoords.LinearRing.Coordinates.Reverse();
                 *
                 *  Polygon kmlpoly = new Polygon() { AltitudeMode = AltitudeMode.relativeToGround, Extrude = false, OuterBoundaryIs = polycoords };
                 *
                 *  Placemark pmpoly = new Placemark();
                 *  pmpoly.Polygon = kmlpoly;
                 *  pmpoly.name = g + " test";
                 *  pmpoly.styleUrl = "#spray";
                 *
                 *  fldr.Add(pmpoly);
                 * }
                 */
                LineString ls = new LineString();
                ls.AltitudeMode = altmode;
                ls.Extrude      = true;
                //ls.Tessellate = true;

                Coordinates coords = new Coordinates();
                coords.AddRange(poslist);

                ls.coordinates = coords;

                Placemark pm = new Placemark();

                string mode = "";
                if (g < modelist.Count)
                {
                    mode = modelist[g];
                }

                pm.name       = g + " Flight Path " + mode;
                pm.styleUrl   = "#yellowLineGreenPoly";
                pm.LineString = ls;

                stylecode = colours[g % (colours.Length - 1)].ToArgb();

                Style style2 = new Style();
                Color color  = Color.FromArgb(0xff, (stylecode >> 16) & 0xff, (stylecode >> 8) & 0xff, (stylecode >> 0) & 0xff);
                log.Info("colour " + color.ToArgb().ToString("X") + " " + color.ToKnownColor().ToString());
                style2.Add(new LineStyle(color, 4));



                pm.AddStyle(style2);

                fldr.Add(pm);
            }

            Folder planes = new Folder();

            planes.name = "Planes";
            fldr.Add(planes);

            Folder waypoints = new Folder();

            waypoints.name = "Waypoints";
            fldr.Add(waypoints);


            LineString lswp = new LineString();

            lswp.AltitudeMode = AltitudeMode.relativeToGround;
            lswp.Extrude      = true;

            Coordinates coordswp = new Coordinates();

            foreach (PointLatLngAlt p1 in cmd)
            {
                coordswp.Add(new Point3D(p1.Lng, p1.Lat, p1.Alt));
            }

            lswp.coordinates = coordswp;

            Placemark pmwp = new Placemark();

            pmwp.name = "Waypoints";
            //pm.styleUrl = "#yellowLineGreenPoly";
            pmwp.LineString = lswp;

            waypoints.Add(pmwp);

            int a = 0;
            int l = -1;

            Model lastmodel = null;

            foreach (Data mod in flightdata)
            {
                l++;
                if (mod.model.Location.latitude == 0)
                {
                    continue;
                }

                if (lastmodel != null)
                {
                    if (lastmodel.Location.Equals(mod.model.Location))
                    {
                        continue;
                    }
                }
                Placemark pmplane = new Placemark();
                pmplane.name = "Plane " + a;

                pmplane.visibility = false;

                Model model = mod.model;
                model.AltitudeMode = altmode;
                model.Scale.x      = 2;
                model.Scale.y      = 2;
                model.Scale.z      = 2;

                try
                {
                    pmplane.description = @"<![CDATA[
              <table>
                <tr><td>Roll: " + model.Orientation.roll + @" </td></tr>
                <tr><td>Pitch: " + model.Orientation.tilt + @" </td></tr>
                <tr><td>Yaw: " + model.Orientation.heading + @" </td></tr>
                <tr><td>WP dist " + mod.ntun[2] + @" </td></tr>
				<tr><td>tar bear "                 + mod.ntun[3] + @" </td></tr>
				<tr><td>nav bear "                 + mod.ntun[4] + @" </td></tr>
				<tr><td>alt error "                 + mod.ntun[5] + @" </td></tr>
              </table>
            ]]>";
                }
                catch { }

                try
                {
                    pmplane.Point = new KmlPoint((float)model.Location.longitude, (float)model.Location.latitude, (float)model.Location.altitude);
                    pmplane.Point.AltitudeMode = altmode;

                    Link link = new Link();
                    link.href = "block_plane_0.dae";

                    model.Link = link;

                    pmplane.Model = model;

                    planes.Add(pmplane);
                }
                catch { } // bad lat long value

                lastmodel = mod.model;

                a++;
            }

            kml.Document.Add(fldr);

            kml.Save(filename);

            // create kmz - aka zip file

            FileStream      fs        = File.Open(filename.ToLower().Replace(".log.kml", ".kmz").Replace(".bin.kml", ".kmz"), FileMode.Create);
            ZipOutputStream zipStream = new ZipOutputStream(fs);

            zipStream.SetLevel(9);             //0-9, 9 being the highest level of compression
            zipStream.UseZip64 = UseZip64.Off; // older zipfile

            // entry 1
            string   entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction
            ZipEntry newEntry  = new ZipEntry(entryName);

            newEntry.DateTime = DateTime.Now;

            zipStream.PutNextEntry(newEntry);

            // Zip the file in buffered chunks
            // the "using" will close the stream even if an exception occurs
            byte[] buffer = new byte[4096];
            using (FileStream streamReader = File.OpenRead(filename))
            {
                StreamUtils.Copy(streamReader, zipStream, buffer);
            }
            zipStream.CloseEntry();

            File.Delete(filename);

            filename = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "block_plane_0.dae";

            // entry 2
            entryName         = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction
            newEntry          = new ZipEntry(entryName);
            newEntry.DateTime = DateTime.Now;

            zipStream.PutNextEntry(newEntry);

            // Zip the file in buffered chunks
            // the "using" will close the stream even if an exception occurs
            buffer = new byte[4096];
            using (FileStream streamReader = File.OpenRead(filename))
            {
                StreamUtils.Copy(streamReader, zipStream, buffer);
            }
            zipStream.CloseEntry();


            zipStream.IsStreamOwner = true;     // Makes the Close also Close the underlying stream
            zipStream.Close();

            positionindex = 0;
            modelist.Clear();
            flightdata.Clear();
            position = new List <Core.Geometry.Point3D> [200];
            cmd.Clear();
        }
Ejemplo n.º 4
0
        public static void ExtractPAK(Stream pakStream, String outDir)
        {
            #region HashSet<String> excludeExtensions = ...

            // TODO: Read this from .gitignore
            HashSet <String> excludeExtensions = new HashSet <String>(StringComparer.InvariantCultureIgnoreCase)
            {
                ".png",
                ".jpg",
                ".tif",
                ".tiff",
                ".gif",
                ".mp3",
                ".flak",
                ".bai",
                ".cfxb",
                ".cfib",
                ".fxcb",
                ".lst",
                ".bin",
                ".usm",       // ???
                ".cax",       // ???
                ".gfx",       // ???
                ".dat",       // Terrain data?
                ".obj",       // Models and Animations
                ".img",       // Models and Animations
                ".anm",       // Models and Animations
                ".cga",       // Models and Animations
                ".cgam",      // Models and Animations
                ".caf",       // Models and Animations
                ".dba",       // Models and Animations
                ".cgf",       // Models and Animations
                ".skin",      // Models and Animations
                ".skinm",     // Models and Animations
                ".chr",       // Models and Animations
                ".chrm",      // Models and Animations
                ".chrparams", // Models and Animations
                ".mtl",       // Models and Animations
                ".swf",       // Flash
                ".ogg",       // Sounds
                ".wem",       // Sounds
                ".bnk",       // Sounds
                ".dds",       // Textures
                ".a",         // Textures
                ".1",         // Textures
                ".2",         // Textures
                ".3",         // Textures
                ".4",         // Textures
                ".5",         // Textures
                ".6",         // Textures
                ".7",         // Textures
                ".8",         // Textures
                ".9",         // Textures
                ".1a",        // Textures
                ".2a",        // Textures
                ".3a",        // Textures
                ".4a",        // Textures
                ".5a",        // Textures
                ".6a",        // Textures
                ".7a",        // Textures
                ".8a",        // Textures
                ".9a",        // Textures
            };

            #endregion

            using (var zipStream = new ZipInputStream(pakStream))
            {
                ZipEntry zipEntry = zipStream.GetNextEntry();
                while (zipEntry != null)
                {
                    String entryFileName = zipEntry.Name;

                    if (excludeExtensions.Contains(Path.GetExtension(entryFileName)))
                    {
                        zipEntry = zipStream.GetNextEntry();
                        continue;
                    }

                    Console.WriteLine("Extracting: {0}", entryFileName);

                    // to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
                    // Optionally match entrynames against a selection list here to skip as desired.
                    // The unpacked length is available in the zipEntry.Size property.

                    Byte[] buffer = new Byte[4096];     // 4K is optimum

                    // Manipulate the output filename here as desired.
                    String fullZipToPath = Path.Combine(outDir, entryFileName);
                    String directoryName = Path.GetDirectoryName(fullZipToPath);
                    if (directoryName.Length > 0)
                    {
                        Directory.CreateDirectory(directoryName);
                    }

                    // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
                    // of the file, but does not waste memory.
                    // The "using" will close the stream even if an exception occurs.
                    using (FileStream streamWriter = File.Create(fullZipToPath))
                    {
                        StreamUtils.Copy(zipStream, streamWriter, buffer);
                    }

                    // TODO: Parse CryXMLB and DataForge files

                    zipEntry = zipStream.GetNextEntry();
                }
            }
        }
Ejemplo n.º 5
0
        public static void CreateArchive(ArchiveOptions archiveOptions, ProcessingEntry processingEntry,
                                         CancellationTokenEx cancellationToken, ReportCompressionStatus reportCompressionStatus)
        {
            var folderName = new Lazy <string>(() =>
            {
                var firstEntry = archiveOptions.Entries[0];
                return((firstEntry.IsDirectory
                    ? new DirectoryInfo(firstEntry.Path).Parent.FullName
                    : new FileInfo(firstEntry.Path).DirectoryName).TrimEnd('\\'));
            });

            Stream outputStream = new FileStream(archiveOptions.ArchivePath, FileMode.Create, FileAccess.ReadWrite);

            switch (archiveOptions.CompressionMethod)
            {
            case CompressionMethod.None:
                //dont wrap the stream
                break;

            case CompressionMethod.Zip:
                using (var zipStream = new ZipOutputStream(outputStream)
                {
                    IsStreamOwner = true
                })
                {
                    zipStream.SetLevel(archiveOptions.CompressionLevel);
                    zipStream.Password = archiveOptions.Password;

                    var folderOffset = folderName.Value.Length;

                    var fileList = new List <FileInfo>();
                    foreach (var entry in archiveOptions.Entries)
                    {
                        if (entry.IsDirectory)
                        {
                            CollectFiles(fileList, new DirectoryInfo(entry.Path));
                        }
                        else
                        {
                            fileList.Add(new FileInfo(entry.Path));
                        }
                    }

                    double totalLength     = fileList.Sum(x => x.Length);
                    long   currentLength   = 0;
                    var    updateStopwatch = Stopwatch.StartNew();

                    void UpdateProgress(float progress)
                    {
                        //important for a lot of small files
                        if (updateStopwatch.ElapsedMilliseconds > 1000)
                        {
                            updateStopwatch.Reset();
                            processingEntry.Progress = progress;
                            processingEntry.Size     = zipStream.Length;
                            ThreadPool.QueueUserWorkItem(state => reportCompressionStatus.Invoke(processingEntry));
                            updateStopwatch.Start();
                        }
                    }

                    foreach (var fileInfo in fileList)
                    {
                        var entryName = ZipEntry.CleanName(fileInfo.FullName.Substring(folderOffset));
                        var zipEntry  = new ZipEntry(entryName)
                        {
                            DateTime   = fileInfo.LastWriteTime,
                            AESKeySize = string.IsNullOrEmpty(archiveOptions.Password) ? 0 : 256,
                            Size       = fileInfo.Length
                        };

                        byte[]     buffer = new byte[4096];
                        FileStream zipEntryStream;
                        try
                        {
                            zipEntryStream = fileInfo.OpenRead();
                        }
                        catch (Exception)
                        {
                            continue;     //access denied
                        }

                        zipStream.PutNextEntry(zipEntry);

                        using (zipEntryStream)
                        {
                            StreamUtils.Copy(zipEntryStream, zipStream, buffer, (sender, args) =>
                            {
                                UpdateProgress((float)((currentLength + args.Processed) / totalLength));
                                args.ContinueRunning = !cancellationToken.IsCanceled;
                            }, TimeSpan.FromSeconds(1), null, null);
                        }

                        if (cancellationToken.IsCanceled)
                        {
                            //force update
                            processingEntry.Progress = -1;
                            ThreadPool.QueueUserWorkItem(state => reportCompressionStatus.Invoke(processingEntry));
                            return;
                        }

                        currentLength += fileInfo.Length;
                        zipStream.CloseEntry();

                        UpdateProgress((float)(currentLength / totalLength));
                    }

                    //force update
                    processingEntry.Size     = zipStream.Length;
                    processingEntry.Progress = 1;
                    ThreadPool.QueueUserWorkItem(state => reportCompressionStatus.Invoke(processingEntry));
                }
                return;

            case CompressionMethod.Gzip:
                var gzipStream = new GZipOutputStream(outputStream)
                {
                    IsStreamOwner = true
                };
                gzipStream.SetLevel(archiveOptions.CompressionLevel);
                gzipStream.Password = archiveOptions.Password;
                outputStream        = gzipStream;
                break;

            case CompressionMethod.Bzip2:
                outputStream = new BZip2OutputStream(outputStream)
                {
                    IsStreamOwner = true
                };
                break;

            default:
                throw new ArgumentException("Unknown compression method: " + archiveOptions.CompressionMethod);
            }

            using (outputStream)
            {
                if (archiveOptions.UseTarPacker)
                {
                    using (var tarOutputStream = new TarOutputStream(outputStream))
                    {
                        var rootPath =
                            Path.GetDirectoryName(archiveOptions.Entries[0].Path).Replace('\\', '/').TrimEnd('/');

                        var fileList = new List <FileInfo>();
                        foreach (var entry in archiveOptions.Entries)
                        {
                            if (entry.IsDirectory)
                            {
                                CollectFiles(fileList, new DirectoryInfo(entry.Path));
                            }
                            else
                            {
                                fileList.Add(new FileInfo(entry.Path));
                            }
                        }

                        var    buffer          = new byte[4096];
                        double totalLength     = fileList.Sum(x => x.Length);
                        long   currentLength   = 0;
                        var    updateStopwatch = Stopwatch.StartNew();

                        foreach (var fileInfo in fileList)
                        {
                            Stream fileStream;
                            try
                            {
                                fileStream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read);
                            }
                            catch (Exception)
                            {
                                continue;
                            }

                            using (fileStream)
                            {
                                var tarEntry = TarEntry.CreateEntryFromFile(fileInfo.FullName);
                                tarEntry.Name = fileInfo.FullName.Substring(rootPath.Length + 1);
                                tarOutputStream.PutNextEntry(tarEntry);

                                StreamUtils.Copy(fileStream, tarOutputStream, buffer, (sender, args) =>
                                {
                                    args.ContinueRunning = !cancellationToken.IsCanceled;
                                    if (updateStopwatch.ElapsedMilliseconds > 1000)
                                    {
                                        updateStopwatch.Reset();
                                        processingEntry.Progress =
                                            (float)((currentLength + args.Processed) / totalLength);
                                        processingEntry.Size = tarOutputStream.Length;
                                        ThreadPool.QueueUserWorkItem(
                                            state => reportCompressionStatus.Invoke(processingEntry));
                                        updateStopwatch.Start();
                                    }
                                },
                                                 TimeSpan.FromSeconds(1), null, null);
                                tarOutputStream.CloseEntry();
                            }

                            currentLength += fileInfo.Length;

                            if (cancellationToken.IsCanceled)
                            {
                                processingEntry.Progress = -1;
                                ThreadPool.QueueUserWorkItem(state => reportCompressionStatus.Invoke(processingEntry));
                                return;
                            }
                        }
                    }
                }
                else
                {
                    var entry = archiveOptions.Entries[0];
                    if (entry.IsDirectory)
                    {
                        throw new ArgumentException("Cannot pack directory without tar/zip");
                    }

                    byte[] dataBuffer = new byte[4096];
                    using (var sourceStream = new FileStream(entry.Path, FileMode.Open, FileAccess.Read))
                        StreamUtils.Copy(sourceStream, outputStream, dataBuffer, (sender, args) =>
                        {
                            //no stopwatch needed because it is only one entry
                            processingEntry.Progress = args.PercentComplete / 100;
                            processingEntry.Size     = outputStream.Length;
                            args.ContinueRunning     = !cancellationToken.IsCanceled;
                            ThreadPool.QueueUserWorkItem(state => reportCompressionStatus.Invoke(processingEntry));
                        }, TimeSpan.FromSeconds(1), null, null);

                    if (cancellationToken.IsCanceled)
                    {
                        //force update
                        processingEntry.Progress = -1;
                        ThreadPool.QueueUserWorkItem(state => reportCompressionStatus.Invoke(processingEntry));
                        return;
                    }
                }

                processingEntry.Size     = outputStream.Length;
                processingEntry.Progress = 1;
                ThreadPool.QueueUserWorkItem(state => reportCompressionStatus.Invoke(processingEntry));
            }
        }
Ejemplo n.º 6
0
        public void NonSuckingServiceManagerSubworker()
        {
            // Thread signal.
            bool complete = false;

            // Webclient
            WebClient webClient = new WebClient();

            // Remember the directory
            string nssmDownloadLink = Program.SourcesInformation["windows"]["nssm"].ToString();

            string[] brokenUrlStrings = nssmDownloadLink.Split('/');
            string   zipName          = brokenUrlStrings[brokenUrlStrings.Length - 1];

            nssmInstallPath = Path.Combine(Program.InstallLocation, zipName.Substring(0, zipName.Length - 4));
            var nssmZipPath = Path.Combine(Program.InstallLocation, zipName);

            // Tell the user what's going to happen
            EasyLog(string.Format("Downloading {0} from {1}",
                                  zipName,
                                  nssmDownloadLink
                                  ));

            // Start the stopwatch.
            _timeStarted = DateTime.Now;

            // Download Percent Changed Event - Update the progress bar
            webClient.DownloadProgressChanged += (senderChild, eChild) =>
            {
                OverallProgress.Maximum = int.Parse(eChild.TotalBytesToReceive.ToString());
                OverallProgress.Value   = int.Parse(eChild.BytesReceived.ToString());
                ProgressText.Text       = string.Format("Downloaded {0}/{1} MiB @ {2} KiB/s",
                                                        Math.Round(eChild.BytesReceived / Math.Pow(1024, 2), 2),
                                                        Math.Round(eChild.TotalBytesToReceive / Math.Pow(1024, 2), 2),
                                                        Math.Round(eChild.BytesReceived / (DateTime.Now - _timeStarted).TotalSeconds / Math.Pow(1024, 1), 2
                                                                   )
                                                        );
            };

            // Download Complete Event
            webClient.DownloadFileCompleted += (senderChild, eChild) =>
            {
                // Tell the user where the file was saved.
                EasyLog(string.Format("{0} was saved to {1}", zipName, nssmZipPath));

                // Create the installation directory if it doesn't exist.
                if (!Directory.Exists(nssmInstallPath))
                {
                    Directory.CreateDirectory(nssmInstallPath);
                    EasyLog("Created Directory: " + nssmInstallPath);
                }

                // Extract the archive
                ZipFile versionZipFile = new ZipFile(File.OpenRead(nssmZipPath));

                // Reset the progress bar.
                OverallProgress.Maximum = int.Parse(versionZipFile.Count.ToString());
                OverallProgress.Value   = 0;

                // Iterate through each object in the archive
                foreach (ZipEntry zipEntry in versionZipFile)
                {
                    // Check if we should pause
                    while (_pauseActions)
                    {
                        Thread.Sleep(10);
                    }

                    // Get the current absolute path
                    string currentPath = Path.Combine(Program.InstallLocation, zipEntry.Name);

                    // Create the directory if needed.
                    if (zipEntry.IsDirectory)
                    {
                        Directory.CreateDirectory(currentPath);
                        EasyLog("Created Directory: " + currentPath);
                    }
                    // Copy the file to the directory.
                    else
                    {
                        // Use a buffer, 4096 bytes seems to be pretty optimal.
                        byte[] buffer    = new byte[4096];
                        Stream zipStream = versionZipFile.GetInputStream(zipEntry);

                        // Copy to and from the buffer, and then to the disk.
                        using (FileStream streamWriter = File.Create(currentPath))
                        {
                            EasyLog("Copying file: " + currentPath);
                            StreamUtils.Copy(zipStream, streamWriter, buffer);
                        }
                    }

                    // Update the progress bar.
                    OverallProgress.Value += 1;

                    // Update the progress text.
                    ProgressText.Text = string.Format("Extracting file {0}/{1}", OverallProgress.Value,
                                                      OverallProgress.Maximum);
                }

                complete = true;
            };

            // Download the file asyncronously.
            webClient.DownloadFileAsync(new Uri(nssmDownloadLink), nssmZipPath);

            while (webClient.IsBusy || !complete)
            {
                Thread.Sleep(1);
            }
        }
Ejemplo n.º 7
0
    //TODO: wrap all the file creation/access parts in try-catches
    bool StageMod(string modpath, string modname)
    {
        if (!File.Exists(modpath))
        {
            return(false);
        }

        string extractTo   = TempExtractionFolderPath;
        string zipfilePath = modpath;

        if (!Directory.Exists(extractTo))
        {
            Directory.CreateDirectory(extractTo);
        }

        bool abort = false;

        try
        {
            Debug.Log("Source zip file: " + zipfilePath);
            Debug.Log("Printing unzipped files");

            ZipFile zip = new ZipFile(File.OpenRead(zipfilePath));
            foreach (ZipEntry e in zip)
            {
                Debug.Log(e.Name);
                byte[] buffer      = new byte[4096];
                Stream zipStream   = zip.GetInputStream(e);
                String fullZipPath = Path.Combine(extractTo, e.Name);
                Debug.Log(fullZipPath + " is your full path");
                if (!e.IsFile)
                {
                    Directory.CreateDirectory(fullZipPath);
                    continue;
                }
                using (FileStream streamWriter = File.Create(fullZipPath)) {
                    StreamUtils.Copy(zipStream, streamWriter, buffer);
                }
            }
        }
        catch (Exception e)
        {
            Debug.LogError("Error extracting mod: " + e.Message);
            System.Windows.Forms.MessageBox.Show("Error extracting mod from " + zipfilePath + " to " + extractTo + " --- Error: " + e.Message);
            abort = true;
        }

        if (abort)
        {
            return(false);
        }

        Debug.Log("Searching for dlls in " + extractTo);
        List <string> dllFiles = FileFinder.FindFiles(extractTo, "dll", true);

        //NOTE: May need to revisit this for mods that have no dll files, if any ever exist
        if (dllFiles.Count < 1)
        {
            Debug.LogError("No dlls found in mod!");
            System.Windows.Forms.MessageBox.Show("No dlls found in mod!");
            return(false);
        }

        stagedPaths[modname] = new List <string>();

        //create a staged path using each dll
        foreach (string dllFile in dllFiles)
        {
            Debug.Log("Mod dll found at: " + dllFile);

            //Parse the path to get the root of the dll
            int startIndex = dllFile.IndexOf("Temp") + "Temp".Length;
            int length     = dllFile.IndexOf('\\', startIndex + 1) - startIndex;

            string localModPath = "";

            Debug.Log("dll path parsing: startIndex = " + startIndex);

            if (length < 0)
            {
                length = 0;
            }
            else
            {
                Debug.Log("dll path parsing: length = " + length);

                localModPath = dllFile.Substring(startIndex, length);
            }

            if (localModPath.TrimEnd('/').Contains("hollow_knight_Data"))
            {
                //for some reason, the root folder of lightbringer is never "extracted" so see if we can kinda cheat here
                stagedPaths[modname].Add(extractTo + "/");
            }
            else
            {
                stagedPaths[modname].Add(extractTo + localModPath + "/");
            }

            Debug.Log("Root folder for dll: " + localModPath);
        }

        Debug.Log("Decompressed and staged " + modname);

        return(true);
    }
Ejemplo n.º 8
0
        void ExtractFileEntry(ZipEntry entry, string targetName)
        {
            bool proceed = true;

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (overwrite_ != Overwrite.Always)
                {
                    if (store.FileExists(targetName))
                    {
                        if ((overwrite_ == Overwrite.Prompt) && (confirmDelegate_ != null))
                        {
                            proceed = confirmDelegate_(targetName);
                        }
                        else
                        {
                            proceed = false;
                        }
                    }
                }

                if (proceed)
                {
                    if (events_ != null)
                    {
                        continueRunning_ = events_.OnProcessFile(entry.Name);
                    }

                    if (continueRunning_)
                    {
                        try {
                            using (var outputStream = store.CreateFile(targetName))
                            {
                                if (buffer_ == null)
                                {
                                    buffer_ = new byte[4096];
                                }
                                if ((events_ != null) && (events_.Progress != null))
                                {
                                    StreamUtils.Copy(zipFile_.GetInputStream(entry), outputStream, buffer_,
                                                     events_.Progress, events_.ProgressInterval, this, entry.Name, entry.Size);
                                }
                                else
                                {
                                    StreamUtils.Copy(zipFile_.GetInputStream(entry), outputStream, buffer_);
                                }

                                if (events_ != null)
                                {
                                    continueRunning_ = events_.OnCompletedFile(entry.Name);
                                }
                            }
                        }
                        catch (Exception ex) {
                            if (events_ != null)
                            {
                                continueRunning_ = events_.OnFileFailure(targetName, ex);
                            }
                            else
                            {
                                continueRunning_ = false;
                                throw;
                            }
                        }
                    }
                }
            }
        }
        public ActionResult CreateBulk(int?CarId, int?ImageType, string ColorHex, HttpPostedFileBase FolderPath)
        {
            var    webRoot     = Server.MapPath("~/");
            string PicturePath = "";

            if (ImageType == 1)
            {
                PicturePath = "Content/Images/CarMake/Image360/interior/";
            }
            else if (ImageType == 2)
            {
                PicturePath = "Content/Images/CarMake/Image360/exterior/";
            }
            var corlorWithOutHash = ColorHex.Substring(1);

            PicturePath = PicturePath + $"{CarId}/{corlorWithOutHash}";
            string TempPath = Path.Combine(webRoot, PicturePath);

            Directory.CreateDirectory(TempPath);


            //// this for access denied
            DirectoryInfo     directory = new DirectoryInfo(TempPath);
            DirectorySecurity security  = directory.GetAccessControl();

            security.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                                                            FileSystemRights.FullControl,
                                                            InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,
                                                            PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
            directory.SetAccessControl(security);
            var path = Path.Combine(TempPath, Path.GetFileName(FolderPath.FileName));

            FolderPath.SaveAs(path);

            string ZipFileName = Path.Combine(TempPath, FolderPath.FileName);

            if (Path.GetExtension(ZipFileName).Equals(".zip"))
            {
                ZipFile file = null;
                try
                {
                    FileStream fs = System.IO.File.OpenRead(ZipFileName);
                    file = new ZipFile(fs);

                    //if (!String.IsNullOrEmpty(password))
                    //{
                    //    // AES encrypted entries are handled automatically
                    //    file.Password = password;
                    //}

                    foreach (ZipEntry zipEntry in file)
                    {
                        if (!zipEntry.IsFile)
                        {
                            // Ignore directories
                            continue;
                        }

                        String entryFileName = zipEntry.Name;
                        // to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
                        // Optionally match entrynames against a selection list here to skip as desired.
                        // The unpacked length is available in the zipEntry.Size property.

                        // 4K is optimum
                        byte[] buffer    = new byte[4096];
                        Stream zipStream = file.GetInputStream(zipEntry);

                        // Manipulate the output filename here as desired.
                        String fullZipToPath = Path.Combine(TempPath, entryFileName);
                        string directoryName = Path.GetDirectoryName(fullZipToPath);

                        if (directoryName.Length > 0)
                        {
                            Directory.CreateDirectory(directoryName);
                        }

                        // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
                        // of the file, but does not waste memory.
                        // The "using" will close the stream even if an exception occurs.
                        using (FileStream streamWriter = System.IO.File.Create(fullZipToPath))
                        {
                            StreamUtils.Copy(zipStream, streamWriter, buffer);
                        }
                    }
                }
                finally
                {
                    if (file != null)
                    {
                        file.IsStreamOwner = true; // Makes close also shut the underlying stream
                        file.Close();              // Ensure we release resources
                    }

                    if (System.IO.File.Exists(ZipFileName))
                    {
                        System.IO.File.Delete(ZipFileName);
                    }
                }

                var model = new Models.CarMakeBulkImages()
                {
                    CarId      = CarId.GetValueOrDefault(),
                    ImageType  = ImageType.GetValueOrDefault(),
                    ColorHex   = ColorHex,
                    FolderPath = PicturePath
                };
                _CarMakeBulkRepo.Insert(model);
            }
            return(RedirectToAction("BulkList"));
        }
Ejemplo n.º 10
0
        private void ExtractFileEntry(ZipEntry entry, string targetName)
        {
            bool proceed = true;

            if (overwrite_ != Overwrite.Always)
            {
                if (File.Exists(targetName))
                {
                    if ((overwrite_ == Overwrite.Prompt) && (confirmDelegate_ != null))
                    {
                        proceed = confirmDelegate_(targetName);
                    }
                    else
                    {
                        proceed = false;
                    }
                }
            }

            if (proceed)
            {
                if (events_ != null)
                {
                    continueRunning_ = events_.OnProcessFile(entry.Name);
                }

                if (continueRunning_)
                {
                    try
                    {
                        using (FileStream outputStream = File.Create(targetName))
                        {
                            if (buffer_ == null)
                            {
                                buffer_ = new byte[4096];
                            }

                            using (var inputStream = zipFile_.GetInputStream(entry))
                            {
                                if ((events_ != null) && (events_.Progress != null))
                                {
                                    StreamUtils.Copy(inputStream, outputStream, buffer_,
                                                     events_.Progress, events_.ProgressInterval, this, entry.Name, entry.Size);
                                }
                                else
                                {
                                    StreamUtils.Copy(inputStream, outputStream, buffer_);
                                }
                            }

                            if (events_ != null)
                            {
                                continueRunning_ = events_.OnCompletedFile(entry.Name);
                            }
                        }

                        if (restoreDateTimeOnExtract_)
                        {
                            switch (entryFactory_.Setting)
                            {
                            case TimeSetting.CreateTime:
                                File.SetCreationTime(targetName, entry.DateTime);
                                break;

                            case TimeSetting.CreateTimeUtc:
                                File.SetCreationTimeUtc(targetName, entry.DateTime);
                                break;

                            case TimeSetting.LastAccessTime:
                                File.SetLastAccessTime(targetName, entry.DateTime);
                                break;

                            case TimeSetting.LastAccessTimeUtc:
                                File.SetLastAccessTimeUtc(targetName, entry.DateTime);
                                break;

                            case TimeSetting.LastWriteTime:
                                File.SetLastWriteTime(targetName, entry.DateTime);
                                break;

                            case TimeSetting.LastWriteTimeUtc:
                                File.SetLastWriteTimeUtc(targetName, entry.DateTime);
                                break;

                            case TimeSetting.Fixed:
                                File.SetLastWriteTime(targetName, entryFactory_.FixedDateTime);
                                break;

                            default:
                                throw new ZipException("Unhandled time setting in ExtractFileEntry");
                            }
                        }

                        if (RestoreAttributesOnExtract && entry.IsDOSEntry && (entry.ExternalFileAttributes != -1))
                        {
                            var fileAttributes = (FileAttributes)entry.ExternalFileAttributes;
                            // TODO: FastZip - Setting of other file attributes on extraction is a little trickier.
                            fileAttributes &= (FileAttributes.Archive | FileAttributes.Normal | FileAttributes.ReadOnly | FileAttributes.Hidden);
                            File.SetAttributes(targetName, fileAttributes);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (events_ != null)
                        {
                            continueRunning_ = events_.OnFileFailure(targetName, ex);
                        }
                        else
                        {
                            continueRunning_ = false;
                            throw;
                        }
                    }
                }
            }
        }
Ejemplo n.º 11
0
        public static void UnZipNativeFile(string zipPath, string outFolder, List <string> exclude, bool check)
        {
            ZipFile zf = null;

            try
            {
                FileStream fs = File.OpenRead(zipPath);
                zf = new ZipFile(fs);
                if (!Directory.Exists(outFolder))
                {
                    Directory.CreateDirectory(outFolder);
                }

                foreach (ZipEntry zipEntry in zf)
                {
                    if (!zipEntry.IsFile)
                    {
                        continue;
                    }
                    if (exclude != null && exclude.Any(zipEntry.Name.StartsWith))
                    {
                        continue;
                    }

                    byte[] buffer    = new byte[4096];  // 4K is optimum
                    Stream zipStream = zf.GetInputStream(zipEntry);

                    string fullZipToPath = Path.Combine(outFolder, zipEntry.Name);
                    string directoryName = Path.GetDirectoryName(fullZipToPath);
                    if (!Directory.Exists(directoryName))
                    {
                        Directory.CreateDirectory(directoryName);
                    }

                    if (check)
                    {
                        if (File.Exists(fullZipToPath))
                        {
                            FileInfo info = new FileInfo(fullZipToPath);
                            if (info.Length == zipEntry.Size)
                            {
                                continue;
                            }
                        }
                    }

                    using (FileStream streamWriter = File.Create(fullZipToPath))
                    {
                        StreamUtils.Copy(zipStream, streamWriter, buffer);
                    }
                }
            }
            finally
            {
                if (zf != null)
                {
                    zf.IsStreamOwner = true; // Makes close also shut the underlying stream
                    zf.Close();              // Ensure we release resources
                }
            }
        }
Ejemplo n.º 12
0
        public static List <string> UnzipAllTo(string path, HttpPostedFileBase file)
        {
            var result = new List <string>();
            var mp     = HttpContext.Current.Server.MapPath(path);
            var p      = mp + file.FileName;

            file.SaveAs(p);
            if (p.EndsWith(".zip"))
            {
                ZipFile zf = null;
                try
                {
                    FileStream fs = File.OpenRead(p);
                    zf = new ZipFile(fs);
                    /*if (!String.IsNullOrEmpty(password)){ zf.Password = password;	}*/
                    foreach (ZipEntry zipEntry in zf)
                    {
                        if (!zipEntry.IsFile)
                        {
                            continue;
                        }
                        String entryFileName = zipEntry.Name;

                        byte[] buffer        = new byte[4096];
                        Stream zipStream     = zf.GetInputStream(zipEntry);
                        String fullZipToPath = Path.Combine(mp, entryFileName);
                        string directoryName = Path.GetDirectoryName(fullZipToPath);
                        if (directoryName.Length > 0)
                        {
                            Directory.CreateDirectory(directoryName);
                        }

                        using (FileStream streamWriter = File.Create(fullZipToPath))
                        {
                            StreamUtils.Copy(zipStream, streamWriter, buffer);
                        }
                        result.Add(entryFileName);
                    }
                }
                catch (Exception e)
                {
                    return(result);
                }
                finally
                {
                    if (zf != null)
                    {
                        zf.IsStreamOwner = true;
                        zf.Close();
                    }
                    try
                    {
                        File.Delete(p);
                    }
                    catch (Exception)
                    {
                    }
                }
            }
            else if (p.EndsWith(".rar"))
            {
                try
                {
                    RarArchive archive = RarArchive.Open(p);
                    foreach (RarArchiveEntry entry in archive.Entries)
                    {
                        string pth = Path.Combine(mp, Path.GetFileName(entry.FilePath));
                        entry.WriteToFile(pth);
                        result.Add(Path.GetFileName(entry.FilePath));
                    }
                }
                catch (Exception e)
                {
                    return(result);
                }
                finally
                {
                    try
                    {
                        File.Delete(p);
                    }
                    catch (Exception)
                    {
                    }
                }
            }
            return(result);
        }
Ejemplo n.º 13
0
        public bool GetFile()
        {
            WebClient client  = new WebClient();
            string    ymlPath = "";

            var  target    = DownloadURL;
            bool isArchive = target.Contains(".zip") || target.Contains(".rar") || target.Contains(".gz");
            var  zipPath   = Path.Combine(TargetPath, "data" + Path.GetExtension(target));

            if (!IsLocalPath(target))
            {
                if (!target.Contains(".zip") && !target.Contains(".gz") && !target.Contains(".rar"))
                {
                    var ext = Path.GetExtension(target);
                    var rx  = new Regex(@"\.[a-zA-z]{1,3}");
                    if (!rx.IsMatch(ext ?? ""))
                    {
                        ext = ".zip";
                    }
                    zipPath = Path.Combine(TargetPath, "data" + ext);
                }
                Info.AddMessage("Запущено скачивание YML файла. Это может занять несколько минут....");
                try
                {
                    client.DownloadFile(target, zipPath);
                }
                catch (Exception e)
                {
                    Info.AddMessage(e.Message, true);
                    Info.AddMessage(e.StackTrace, true);
                    Info.EndDate = DateTime.Now;
                    return(false);
                }
                Info.AddMessage("Файл скачан.");
            }
            else
            {
                zipPath = target;
            }
            //криво
            if (!IsLocalPath(target) && !target.Contains(".zip") && !target.Contains(".gz"))
            {
                target = "data.zip";
            }
            if (isArchive)
            {
                if (target.EndsWith(".gz"))
                {
                    try
                    {
                        Info.AddMessage("Распаковка архива....");
                        byte[] dataBuffer = new byte[4096];
                        using (Stream fs = new FileStream(zipPath, FileMode.Open, FileAccess.Read))
                        {
                            using (GZipInputStream gzipStream = new GZipInputStream(fs))
                            {
                                ymlPath        = Path.Combine(TargetPath, "catalog.yml");
                                ResultFileName = ymlPath;
                                using (FileStream fsOut = System.IO.File.Create(ymlPath))
                                {
                                    StreamUtils.Copy(gzipStream, fsOut, dataBuffer);
                                }
                            }
                        }
                        Info.AddMessage("Архив распакован....");
                    }
                    catch (Exception e)
                    {
                        Info.AddMessage(e.Message, true);
                        Info.AddMessage(e.StackTrace, true);
                        Info.EndDate = DateTime.Now;
                        return(false);
                    }
                    finally
                    {
                        File.Delete(zipPath);
                    }
                }
                else if (target.EndsWith(".zip"))
                {
                    ZipFile zf = null;
                    try
                    {
                        Info.AddMessage("Распаковка архива....");
                        FileStream fs = File.OpenRead(zipPath);
                        zf = new ZipFile(fs);
                        /*if (!String.IsNullOrEmpty(password)){ zf.Password = password;	}*/
                        foreach (ZipEntry zipEntry in zf)
                        {
                            if (!zipEntry.IsFile)
                            {
                                continue;
                            }
                            String entryFileName = zipEntry.Name;
                            byte[] buffer        = new byte[4096];
                            Stream zipStream     = zf.GetInputStream(zipEntry);
                            String fullZipToPath = Path.Combine(TargetPath, entryFileName);
                            if (!fullZipToPath.Contains(".doc"))
                            {
                                ResultFileName = fullZipToPath;
                            }
                            string directoryName = Path.GetDirectoryName(fullZipToPath);
                            if (directoryName.Length > 0)
                            {
                                Directory.CreateDirectory(directoryName);
                            }

                            using (FileStream streamWriter = File.Create(fullZipToPath))
                            {
                                StreamUtils.Copy(zipStream, streamWriter, buffer);
                            }
                        }
                        Info.AddMessage("Архив распакован....");
                    }
                    catch (Exception e)
                    {
                        Info.AddMessage(e.Message, true);
                        Info.AddMessage(e.StackTrace, true);
                        Info.EndDate = DateTime.Now;
                        return(false);
                    }
                    finally
                    {
                        if (zf != null)
                        {
                            zf.IsStreamOwner = true;
                            zf.Close();
                        }
                        try
                        {
                            File.Delete(zipPath);
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
                else if (target.EndsWith(".rar"))
                {
                    try
                    {
                        Info.AddMessage("Распаковка архива....");

                        RarArchive archive = RarArchive.Open(zipPath);
                        foreach (RarArchiveEntry entry in archive.Entries)
                        {
                            string path = Path.Combine(TargetPath, Path.GetFileName(entry.FilePath));
                            entry.WriteToFile(path);
                            ResultFileName = path;
                        }
                        Info.AddMessage("Архив распакован....");
                    }
                    catch (Exception e)
                    {
                        Info.AddMessage(e.Message, true);
                        Info.AddMessage(e.StackTrace, true);
                        Info.EndDate = DateTime.Now;
                        return(false);
                    }
                    finally
                    {
                        try
                        {
                            File.Delete(zipPath);
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
                else
                {
                    ResultFileName = zipPath;
                }
            }
            else
            {
                ResultFileName = zipPath;
            }
            return(true);
        }
Ejemplo n.º 14
0
        private void ReloadRepos()
        {
            SplashScreen splash = new SplashScreen();

            splash.Show();
            splash.Select();
            RepoBox.ClearSelected();
            Packages.ClearSelected();

            rep      = new Repo();
            boxes    = new Dictionary <string, CheckedListBox>();
            repos    = new List <Repo>();
            selected = new Dictionary <string, Package>();
            string[] repofiles = Directory.GetFiles(Environment.CurrentDirectory, "*.repo");
            Parallel.ForEach(repofiles, (r) => {
                bool cont     = false;
                FileStream fs = File.OpenRead(r);
                ZipFile zf    = new ZipFile(fs);

                string path = zf.Name.Replace(".repo", "");

                foreach (ZipEntry zipEntry in zf)
                {
                    try {
                        string name = zipEntry.Name;

                        byte[] buffer    = new byte[4096];
                        Stream zipStream = zf.GetInputStream(zipEntry);

                        String fullZipToPath = Path.Combine(path, name);
                        Console.WriteLine(fullZipToPath);

                        string directoryName = Path.GetDirectoryName(fullZipToPath);
                        if (directoryName.Length > 0)
                        {
                            Directory.CreateDirectory(directoryName);
                        }

                        using (FileStream streamWriter = File.Create(fullZipToPath)) {
                            StreamUtils.Copy(zipStream, streamWriter, buffer);
                        }
                    } catch (DirectoryNotFoundException ex) {
                        Console.WriteLine(ex.Message);
                        cont = true;
                        break;
                    } catch (FileNotFoundException ex) {
                        Console.WriteLine(ex.Message);
                        cont = true;
                        break;
                    }
                }
                if (cont)
                {
                    return;
                }
                string n         = zf.Name;
                zf.IsStreamOwner = true;
                zf.Close();

                try {
                    string data    = path + "/data.repodata";
                    Repo toadd     = ObjectSaver.ReadFromXmlFile <Repo>(data);
                    toadd.selected = new List <Package>();
                    toadd.sel      = new List <Package>();
                    repos.Add(toadd);

                    CheckedListBox b = new CheckedListBox();
                    foreach (Package pak in toadd.packages.Values)
                    {
                        b.Items.Add(pak);
                    }
                    boxes.Add(toadd.name, b);
                } catch (FileNotFoundException ex) {
                    File.Delete(n);
                    Console.WriteLine(ex.Message);
                    return;
                }
                Directory.Delete(path, true);
            });
            ReloadRepoBox();

            splash.Hide();
            splash.Close();
            this.Show();
            this.Select();
        }
        /// <summary>
        ///  <para>Loads TAI from given Zip-File and Entry and creates & loads Sprites from it.</para>
        /// </summary>
        private IEnumerable <KeyValuePair <string, Sprite> > LoadSpritesFrom(ZipFile zipFile, ZipEntry taiEntry)
        {
            var loadedSprites = new List <KeyValuePair <string, Sprite> >();

            var byteBuffer = new byte[zipBufferSize];

            Stream zipStream = zipFile.GetInputStream(taiEntry);

            var memStream = new MemoryStream();

            StreamUtils.Copy(zipStream, memStream, byteBuffer);
            memStream.Position = 0;

            var    taiReader = new StreamReader(memStream, true);
            string loadedTAI = taiReader.ReadToEnd();

            memStream.Close();
            zipStream.Close();
            taiReader.Close();
            memStream.Dispose();
            zipStream.Dispose();
            taiReader.Dispose();

            string[] splitContents = Regex.Split(loadedTAI, "\r\n"); //Split by newlines.

            foreach (string line in splitContents)
            {
                if (String.IsNullOrWhiteSpace(line))
                {
                    continue;
                }

                string[] splitLine = line.Split(',');
                string[] fullPath  = Regex.Split(splitLine[0], "\t");

                string PlatformPathname = SS14.Shared.Utility.PlatformTools.SanePath(fullPath[0]);

                string originalName = Path.GetFileNameWithoutExtension(PlatformPathname).ToLowerInvariant();
                //The name of the original picture without extension, before it became part of the atlas.
                //This will be the name we can find this under in our Resource lists.

                string[] splitResourceName = fullPath[2].Split('.');

                string imageName = splitResourceName[0].ToLowerInvariant();

                if (!TextureCache.Textures.ContainsKey(imageName))
                {
                    continue; //Image for this sprite does not exist. Possibly set to defered later.
                }
                Texture atlasTex = TextureCache.Textures[imageName].Texture;
                //Grab the image for the sprite from the cache.

                var info = new SpriteInfo();
                info.Name = originalName;

                float offsetX = 0;
                float offsetY = 0;
                float sizeX   = 0;
                float sizeY   = 0;

                if (splitLine.Length > 8) //Separated with ','. This causes some problems and happens on some EU PCs.
                {
                    offsetX = float.Parse(splitLine[3] + "." + splitLine[4], CultureInfo.InvariantCulture);
                    offsetY = float.Parse(splitLine[5] + "." + splitLine[6], CultureInfo.InvariantCulture);
                    sizeX   = float.Parse(splitLine[8] + "." + splitLine[9], CultureInfo.InvariantCulture);
                    sizeY   = float.Parse(splitLine[10] + "." + splitLine[11], CultureInfo.InvariantCulture);
                }
                else
                {
                    offsetX = float.Parse(splitLine[3], CultureInfo.InvariantCulture);
                    offsetY = float.Parse(splitLine[4], CultureInfo.InvariantCulture);
                    sizeX   = float.Parse(splitLine[6], CultureInfo.InvariantCulture);
                    sizeY   = float.Parse(splitLine[7], CultureInfo.InvariantCulture);
                }

                info.Offsets = new Vector2((float)Math.Round(offsetX * atlasTex.Size.X, 1),
                                           (float)Math.Round(offsetY * atlasTex.Size.Y, 1));
                info.Size = new Vector2((float)Math.Round(sizeX * atlasTex.Size.X, 1),
                                        (float)Math.Round(sizeY * atlasTex.Size.Y, 1));

                if (!_spriteInfos.ContainsKey(originalName))
                {
                    _spriteInfos.Add(originalName, info);
                }

                loadedSprites.Add(new KeyValuePair <string, Sprite>(originalName,
                                                                    new Sprite(atlasTex, new SFML.Graphics.IntRect((int)info.Offsets.X, (int)info.Offsets.Y, (int)info.Size.X, (int)info.Size.Y))));
            }

            return(loadedSprites);
        }
Ejemplo n.º 16
0
        private bool ExtractVersion(ICSharpCode.SharpZipLib.Zip.ZipFile archive)
        {
            string mod           = "";
            string json_filename = null;

            if (Global.isMultiMC)
            {
                json_filename = "version-multimc.json";
                if (Global.isForge)
                {
                    json_filename = "version-multimc-forge.json";
                }
            }
            else if (Global.isForge)
            {
                json_filename = "version-forge.json";
                mod           = "-forge";
            }
            else
            {
                if (Global.isShadersMod)
                {
                    json_filename = "version-shadersmod.json";
                    mod           = "-shadersmod";
                }
                else
                {
                    json_filename = "version.json";
                }
            }

            if (json_filename == null)
            {
                log("Invalid Options!");
                return(false);
            }

            ICSharpCode.SharpZipLib.Zip.ZipEntry version_jar = null;
            JObject version_json = null;

            foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry entry in archive)
            {
                if (entry.Name.ToLower() == "version.jar")
                {
                    version_jar = entry;
                    continue;
                }
                if (entry.Name.ToLower() == "version")
                {
                    var txt = new StreamReader(archive.GetInputStream(entry)).ReadToEnd();
                    var pts = txt.Split(':');
                    version_id = pts[0];
                    continue;
                }
            }

            if (version_jar == null || version_id == null)
            {
                log("Invalid archive!");
                return(false);
            }

            version_id += mod;

            foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry entry in archive)
            {
                if (entry.Name.ToLower() == json_filename)
                {
                    try {
                        var txt = new StreamReader(archive.GetInputStream(entry)).ReadToEnd();
                        txt          = txt.Replace("$FILE", version_id);
                        version_json = JObject.Parse(txt);
                    } catch (Exception ex) {
                        log("Failed parsing version json! " + ex.Message);
                    }
                    continue;
                }
            }

            if (version_json == null)
            {
                log("Invalid archive!");
                return(false);
            }

            //modify json args if needed
            try {
                string args = (string)version_json["minecraftArguments"];

                if (args != null)
                {
                    if (Global.isKatVR)
                    {
                        args += " --katvr";
                    }
                    if (Global.isKiosk)
                    {
                        args += " --kiosk";
                    }
                    version_json["minecraftArguments"] = args;
                }

                if (Global.isMultiMC)
                {
                    version_json.Remove("id");
                }

                JArray libs = (JArray)version_json["libraries"];
                //Since this installer does not download Optifine, inject the url into any existing json not yet updated.
                foreach (var lib in libs)
                {
                    if (lib["name"].ToString().Contains("optifine:OptiFine"))
                    {
                        if (lib["url"] == null)
                        {
                            lib["url"] = "http://vivecraft.org/jar/";
                        }

                        if (lib["MMC-hint"] != null)
                        {
                            lib["MMC-hint"].Parent.Remove();
                        }

                        if (!lib["name"].ToString().Contains("_LIB"))
                        {
                            lib["name"] = lib["name"] + "_LIB";
                        }
                    }
                }

                /*if(isMultiMC && useForge.isSelected()) {
                 *  JSONArray tw = (JSONArray) root.get("+tweakers");
                 *  tw = new JSONArray();
                 *  tw.put("org.vivecraft.tweaker.MinecriftForgeTweaker");
                 *  tw.put("net.minecraftforge.fml.common.launcher.FMLTweaker");
                 *  tw.put("optifine.OptiFineForgeTweaker");
                 *  root.put("+tweakers", tw);
                 * }*/
            } catch (Exception e) {
                log("Error modifying version json! " + e.Message);
            }

            //write version json
            try {
                string ver_dir = null;
                if (Global.isMultiMC)
                {
                    ver_dir    = Path.Combine(Global.mmcinst, "patches");
                    version_id = "vivecraft";
                }
                else
                {
                    ver_dir = Path.Combine(Global.targetDir, "versions", version_id);
                }

                if (!Directory.Exists(ver_dir))
                {
                    Directory.CreateDirectory(ver_dir);
                }
                string ver_json_file = Path.Combine(ver_dir, version_id + ".json");
                File.WriteAllText(ver_json_file, version_json.ToString(Formatting.Indented));
            } catch (Exception ex) {
                log("Failed writing version json! " + ex.Message);
            }

            //write lib jar
            try {
                string lib_dir = Path.Combine(Global.targetDir, "libraries", "com", "mtbs3d", "minecrift", Config.VIVECRAFT_VERSION);
                if (Global.isMultiMC)
                {
                    lib_dir = Path.Combine(Global.mmcinst, "libraries");
                }

                if (!Directory.Exists(lib_dir))
                {
                    Directory.CreateDirectory(lib_dir);
                }

                string ver_file = Path.Combine(lib_dir, "minecrift-" + Config.VIVECRAFT_VERSION + ".jar");

                if (File.Exists(ver_file))
                {
                    File.Delete(ver_file);
                }

                using (var reader = archive.GetInputStream(version_jar)) {
                    using (var writer = File.OpenWrite(ver_file)) {
                        StreamUtils.Copy(reader, writer, new byte[2048]);
                    }
                }
                return(true);
            } catch (Exception e) {
                log("Error writing library jar! " + e.Message);
            }

            return(false);
        }
Ejemplo n.º 17
0
        public async Task ExecuteAsync(CommandLineArgs commandLineArgs)
        {
            var projectName = NamespaceHelper.NormalizeNamespace(commandLineArgs.Target);

            if (projectName == null)
            {
                throw new CliUsageException(
                          "Project name is missing!" +
                          Environment.NewLine + Environment.NewLine +
                          GetUsageInfo()
                          );
            }

            Logger.LogInformation("Creating your project...");
            Logger.LogInformation("Project name: " + projectName);

            var template = commandLineArgs.Options.GetOrNull(Options.Template.Short, Options.Template.Long);

            if (template != null)
            {
                Logger.LogInformation("Template: " + template);
            }

            var version = commandLineArgs.Options.GetOrNull(Options.Version.Short, Options.Version.Long);

            if (version != null)
            {
                Logger.LogInformation("Version: " + version);
            }

            var isTiered = commandLineArgs.Options.ContainsKey(Options.Tiered.Long);

            if (isTiered)
            {
                Logger.LogInformation("Tiered: yes");
            }

            var databaseProvider = GetDatabaseProvider(commandLineArgs);

            if (databaseProvider != DatabaseProvider.NotSpecified)
            {
                Logger.LogInformation("Database provider: " + databaseProvider);
            }

            var uiFramework = GetUiFramework(commandLineArgs);

            if (uiFramework != UiFramework.NotSpecified)
            {
                Logger.LogInformation("UI Framework: " + uiFramework);
            }

            var connectionString = GetConnectionString(commandLineArgs);

            if (connectionString != null)
            {
                Logger.LogInformation("Connection string: " + connectionString);
            }

            var mobileApp = GetMobilePreference(commandLineArgs);

            if (mobileApp != MobileApp.None)
            {
                Logger.LogInformation("Mobile App: " + mobileApp);
            }

            var gitHubLocalRepositoryPath = commandLineArgs.Options.GetOrNull(Options.GitHubLocalRepositoryPath.Long);

            if (gitHubLocalRepositoryPath != null)
            {
                Logger.LogInformation("GitHub Local Repository Path: " + gitHubLocalRepositoryPath);
            }

            var templateSource = commandLineArgs.Options.GetOrNull(Options.TemplateSource.Short, Options.TemplateSource.Long);

            if (templateSource != null)
            {
                Logger.LogInformation("Template Source: " + templateSource);
            }

            var createSolutionFolder = (commandLineArgs.Options.GetOrNull(Options.CreateSolutionFolder.Short, Options.CreateSolutionFolder.Long) ?? "true").ToLowerInvariant() != "false";

            if (!createSolutionFolder)
            {
                Logger.LogInformation("Create Solution Folder: no");
            }

            var outputFolder = commandLineArgs.Options.GetOrNull(Options.OutputFolder.Short, Options.OutputFolder.Long);

            var outputFolderRoot =
                outputFolder != null?Path.GetFullPath(outputFolder) : Directory.GetCurrentDirectory();

            outputFolder = createSolutionFolder ?
                           Path.Combine(outputFolderRoot, SolutionName.Parse(projectName).FullName) :
                           outputFolderRoot;

            Volo.Abp.IO.DirectoryHelper.CreateIfNotExists(outputFolder);

            Logger.LogInformation("Output folder: " + outputFolder);

            commandLineArgs.Options.Add(CliConsts.Command, commandLineArgs.Command);

            var result = await TemplateProjectBuilder.BuildAsync(
                new ProjectBuildArgs(
                    SolutionName.Parse(projectName),
                    template,
                    version,
                    databaseProvider,
                    uiFramework,
                    mobileApp,
                    gitHubLocalRepositoryPath,
                    templateSource,
                    commandLineArgs.Options,
                    connectionString
                    )
                );

            using (var templateFileStream = new MemoryStream(result.ZipContent))
            {
                using (var zipInputStream = new ZipInputStream(templateFileStream))
                {
                    var zipEntry = zipInputStream.GetNextEntry();
                    while (zipEntry != null)
                    {
                        if (string.IsNullOrWhiteSpace(zipEntry.Name))
                        {
                            zipEntry = zipInputStream.GetNextEntry();
                            continue;
                        }

                        var fullZipToPath = Path.Combine(outputFolder, zipEntry.Name);
                        var directoryName = Path.GetDirectoryName(fullZipToPath);

                        if (!string.IsNullOrEmpty(directoryName))
                        {
                            Directory.CreateDirectory(directoryName);
                        }

                        var fileName = Path.GetFileName(fullZipToPath);
                        if (fileName.Length == 0)
                        {
                            zipEntry = zipInputStream.GetNextEntry();
                            continue;
                        }

                        var buffer = new byte[4096]; // 4K is optimum
                        using (var streamWriter = File.Create(fullZipToPath))
                        {
                            StreamUtils.Copy(zipInputStream, streamWriter, buffer);
                        }

                        zipEntry = zipInputStream.GetNextEntry();
                    }
                }
            }

            Logger.LogInformation($"'{projectName}' has been successfully created to '{outputFolder}'");
        }
Ejemplo n.º 18
0
        public bool installForge()
        {
            if (Global.customJavaPath == null)
            {
                if (MessageBox.Show(this, "The installer could not locate a java runtime, the Forge isntaller may not run. Continue?"
                                    , "No Java", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                {
                    return(false);
                }
                Global.customJavaPath = "";
            }

            log("Downloading Forge " + Config.FULL_FORGE_VERSION + "");

            var dir  = Path.GetTempPath();
            var file = Config.FORGE_FILE;
            var path = Path.Combine(dir, file);

            byte[] jar = null;
            try {
                jar = Util.getWebBinarywithTimeout(Config.FORGE_URL, 10);
            } catch (Exception ex) {
                log("Error downloading Forge " + ex.Message);
                return(false);
            }

            try {
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
            } catch (Exception ex) {
                log("Error downloading Forge " + ex.Message);
                return(false);
            }


            try {
                using (var reader = new MemoryStream(jar)) {
                    using (var writer = File.OpenWrite(path)) {
                        StreamUtils.Copy(reader, writer, new byte[2048]);
                    }
                }
            } catch (Exception ex) {
                log("Error downloading Forge " + ex.Message);
                return(false);
            }

            prog(5);
            log("Launching Forge Installer " + Config.FORGE_FILE + "...");

            try {
                //TODO: detect no system java and run using MC captive.
                var proc = Process.Start(Path.Combine(Global.customJavaPath, "javaw"), "-jar " + path);
                //TODO do I care about stdout, stderr?
                proc.WaitForExit();
                return(checkForge());
            } catch (Exception ex) {
                log("This shouldn't happen " + ex.Message);
            } finally {
                try { //cleanup
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }
                    if (File.Exists(path + ".log")) //i hate this thing.
                    {
                        File.Delete(path + ".log");
                    }
                } catch (Exception) {
                }
            }

            return(false);
        }
Ejemplo n.º 19
0
        public void SpecteroDownloaderSubworker()
        {
            // Thread signal.
            bool complete = false;

            // Tell the user what's going to happen
            EasyLog(string.Format("Downloading version {0} ({1} release) from {2}",
                                  Program.Version,
                                  Program.Channel,
                                  _downloadLink
                                  ));

            // Webclient for file donwloading.
            WebClient webClient = new WebClient();

            // Start the stopwatch.
            _timeStarted = DateTime.Now;

            // Update the progress bar.
            webClient.DownloadProgressChanged += (senderChild, eChild) =>
            {
                OverallProgress.Maximum = int.Parse(eChild.TotalBytesToReceive.ToString());
                OverallProgress.Value   = int.Parse(eChild.BytesReceived.ToString());
                ProgressText.Text       = string.Format("Downloaded {0}/{1} MiB @ {2} KiB/s",
                                                        Math.Round(eChild.BytesReceived / Math.Pow(1024, 2), 2),
                                                        Math.Round(eChild.TotalBytesToReceive / Math.Pow(1024, 2), 2),
                                                        Math.Round(eChild.BytesReceived / (DateTime.Now - _timeStarted).TotalSeconds / Math.Pow(1024, 1), 2
                                                                   )
                                                        );
            };

            // Define a rule to the webclient to change a boolean when the download is done.
            webClient.DownloadFileCompleted += (senderChild, eChild) =>
            {
                // Tell the user where the file was saved.
                EasyLog(string.Format("{0} was saved to {1}", _zipFilename, _absoluteZipPath));

                // Extract the archive
                ZipFile versionZipFile = new ZipFile(File.OpenRead(_absoluteZipPath));

                // Reset the progress bar.
                OverallProgress.Maximum = int.Parse(versionZipFile.Count.ToString());
                OverallProgress.Value   = 0;

                string workingDirectory = Path.Combine(_absoluteInstallationPath, Program.Version);
                if (!Directory.Exists(workingDirectory))
                {
                    Directory.CreateDirectory(workingDirectory);
                }

                // Iterate through each object in the archive
                foreach (ZipEntry zipEntry in versionZipFile)
                {
                    // Check if we should pause
                    while (_pauseActions)
                    {
                        Thread.Sleep(10);
                    }

                    // Get the current absolute path
                    string currentPath = Path.Combine(workingDirectory, zipEntry.Name);

                    // Create the directory if needed.
                    if (zipEntry.IsDirectory)
                    {
                        Directory.CreateDirectory(currentPath);
                        EasyLog("Created Directory: " + currentPath);
                    }
                    // Copy the file to the directory.
                    else
                    {
                        // Use a buffer, 4096 bytes seems to be pretty optimal.
                        byte[] buffer    = new byte[4096];
                        Stream zipStream = versionZipFile.GetInputStream(zipEntry);

                        // Copy to and from the buffer, and then to the disk.
                        using (FileStream streamWriter = File.Create(currentPath))
                        {
                            EasyLog("Copying file: " + currentPath);
                            StreamUtils.Copy(zipStream, streamWriter, buffer);
                        }
                    }

                    // Update the progress bar.
                    OverallProgress.Value += 1;

                    // Update the progress text.
                    ProgressText.Text = string.Format("Extracting file {0}/{1}", OverallProgress.Value,
                                                      OverallProgress.Maximum);
                }

                complete = true;
            };

            // Download the file asyncronously.
            webClient.DownloadFileAsync(new Uri(_downloadLink), _absoluteZipPath);

            while (webClient.IsBusy || !complete)
            {
                Thread.Sleep(1);
            }
        }
Ejemplo n.º 20
0
        private static void ExtractZip(string pathTarget, string pathExtractTo, string password = "")
        {
            /*
             */
            ZipFile zf = null;

            try
            {
                FileStream fs = File.OpenRead(pathTarget);
                zf = new ZipFile(fs);
                if (!String.IsNullOrEmpty(password))
                {
                    zf.Password = password;     // AES encrypted entries are handled automatically
                }

                long totalSize = zf.Count;
                long totalRead = 0;

                foreach (ZipEntry zipEntry in zf)
                {
                    if (!zipEntry.IsFile)
                    {
                        continue;           // Ignore directories
                    }
                    String entryFileName = zipEntry.Name;
                    // to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
                    // Optionally match entrynames against a selection list here to skip as desired.
                    // The unpacked length is available in the zipEntry.Size property.

                    byte[] buffer    = new byte[4096];  // 4K is optimum
                    Stream zipStream = zf.GetInputStream(zipEntry);

                    // Manipulate the output filename here as desired.
                    String fullZipToPath = Path.Combine(pathExtractTo, entryFileName);
                    string directoryName = Path.GetDirectoryName(fullZipToPath);
                    if (directoryName.Length > 0)
                    {
                        Directory.CreateDirectory(directoryName);
                    }

                    // Update progress text
                    GUI.ProgressText = ProgressText + entryFileName;

                    // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
                    // of the file, but does not waste memory.
                    // The "using" will close the stream even if an exception occurs.
                    using (FileStream streamWriter = File.Create(fullZipToPath))
                    {
                        StreamUtils.Copy(zipStream, streamWriter, buffer);
                    }

                    totalRead   += 1;
                    GUI.Progress = MainWindowViewModel.GetProgress(totalRead, totalSize);
                }
            }
            finally
            {
                if (zf != null)
                {
                    zf.IsStreamOwner = true; // Makes close also shut the underlying stream
                    zf.Close();              // Ensure we release resources
                }
            }
        }
Ejemplo n.º 21
0
        private static byte[] BuildHeaderFromList(byte[] headerString, List <HeaderEntry> files, uint numFolders, uint numFiles, uint namesLength)
        {
            uint startPos = g_demoVol ? 0xcu : 0x14u;
            // first phase of the vol, offsets to actual info
            // one for each file, plus three for a directory
            // (its name offset, number of entries, the parent location)
            //uint fileInfoOffset = startPos + ((numFiles + (numFolders * 3)) * 4);
            // first phase of the vol, offsets to actual info
            // one for each file system entry (either dir or file), plus three for a directory
            // (its name offset, number of entries, the parent location)
            uint fileInfoOffset = startPos + (((numFiles + numFolders) + (numFolders * 3)) * 4);
            //
            // The second set of data is three/four (for the demo) entries per normal file
            // and four per compressed file
            //
            uint numCompressedUint        = (uint)g_numCompressed;
            uint nonCompressedFileEntries = g_demoVol ? 4u : 3u;
            uint nameOffset = fileInfoOffset + (((numCompressedUint * 4) + ((numFiles - numCompressedUint) * nonCompressedFileEntries)) * 4);

            // The names are aligned to a 0x10 boundary, so do that
            nameOffset = (nameOffset + 0xfu) & ~0xfu;
            // the file data is aligned to sectors, so do that
            uint fileDataOffset = nameOffset + namesLength;

            fileDataOffset = (fileDataOffset + 0x7ffu) & ~0x7ffu;

            MemoryStream headerStream = new MemoryStream((int)fileDataOffset);
            BinaryWriter headerWriter = new BinaryWriter(headerStream);

            // rofs string
            headerWriter.Write(headerString);
            // always 2
            headerWriter.Write((ushort)2);
            // version? field, 1 for demo, 2 for release
            ushort ver = 1;

            // not demo
            if (!g_demoVol)
            {
                ver = 2;
            }
            headerWriter.Write(ver);
            // whole header size
            headerWriter.Write(nameOffset + namesLength + 1);
            if (!g_demoVol)
            {
                // names offset, this is weird as in the demo, the value is for the byte /after/ the names start
                // whereas in the full game, it's for the byte /before/
                headerWriter.Write(g_demoVol ? nameOffset + 1 : nameOffset - 1);
                // full game has an extra field
                // don't know what it is though
                headerWriter.Write((uint)0x3532u);
            }

            MemoryStream nameStream = new MemoryStream((int)(fileDataOffset - nameOffset));
            BinaryWriter names      = new BinaryWriter(nameStream);

            startPos += (uint)((3 + files[0].children.Count) * 4);
            WriteNewDirectory(files[0], 0, ref startPos, ref fileInfoOffset, ref fileDataOffset, nameOffset, headerWriter, names, null);
            headerWriter.Flush();
            names.Flush();

            byte[] buffer = new byte[4096];

            headerStream.Seek(nameOffset, SeekOrigin.Begin);
            nameStream.Seek(0, SeekOrigin.Begin);
            StreamUtils.Copy(nameStream, headerStream, buffer);

            return(headerStream.ToArray());
        }
Ejemplo n.º 22
0
        public async Task ExecuteAsync(CommandLineArgs commandLineArgs)
        {
            if (commandLineArgs.Target == null)
            {
                throw new CliUsageException(
                          "Project name is missing!" +
                          Environment.NewLine + Environment.NewLine +
                          GetUsageInfo()
                          );
            }

            Logger.LogInformation("Creating your project...");
            Logger.LogInformation("Project name: " + commandLineArgs.Target);

            var version = commandLineArgs.Options.GetOrNull(Options.Version.Short, Options.Version.Long);

            if (version != null)
            {
                Logger.LogInformation("Version: " + version);
            }


            var gitHubLocalRepositoryPath = commandLineArgs.Options.GetOrNull(Options.GitHubLocalRepositoryPath.Long);

            if (gitHubLocalRepositoryPath != null)
            {
                Logger.LogInformation("GitHub Local Repository Path: " + gitHubLocalRepositoryPath);
            }

            var outputFolder = commandLineArgs.Options.GetOrNull(Options.OutputFolder.Short, Options.OutputFolder.Long);

            outputFolder = Path.Combine(outputFolder != null ? Path.GetFullPath(outputFolder) : Directory.GetCurrentDirectory(),
                                        SolutionName.Parse(commandLineArgs.Target).FullName);

            if (!Directory.Exists(outputFolder))
            {
                Directory.CreateDirectory(outputFolder);
            }

            Logger.LogInformation("Output folder: " + outputFolder);

            commandLineArgs.Options.Add(CliConsts.Command, commandLineArgs.Command);

            var result = await TemplateProjectBuilder.BuildAsync(
                new ProjectBuildArgs(
                    SolutionName.Parse(commandLineArgs.Target),
                    "module",
                    version,
                    gitHubLocalRepositoryPath,
                    commandLineArgs.Options
                    )
                );

            using (var templateFileStream = new MemoryStream(result.ZipContent))
            {
                using (var zipInputStream = new ZipInputStream(templateFileStream))
                {
                    var zipEntry = zipInputStream.GetNextEntry();
                    while (zipEntry != null)
                    {
                        var fullZipToPath = Path.Combine(outputFolder, zipEntry.Name);
                        var directoryName = Path.GetDirectoryName(fullZipToPath);

                        if (!string.IsNullOrEmpty(directoryName))
                        {
                            Directory.CreateDirectory(directoryName);
                        }

                        var fileName = Path.GetFileName(fullZipToPath);
                        if (fileName.Length == 0)
                        {
                            zipEntry = zipInputStream.GetNextEntry();
                            continue;
                        }

                        var buffer = new byte[4096]; // 4K is optimum
                        using (var streamWriter = File.Create(fullZipToPath))
                        {
                            StreamUtils.Copy(zipInputStream, streamWriter, buffer);
                        }

                        zipEntry = zipInputStream.GetNextEntry();
                    }
                }
            }

            Logger.LogInformation($"'{commandLineArgs.Target}' has been successfully created to '{outputFolder}'");
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Extract files to disk
        /// </summary>
        /// <remarks>
        /// At the point of authoring (Jan 2019) the BCL does not implement tar-files or bz2.
        /// https://github.com/dotnet/corefx/issues/3253 has been discussed since Sept 2015
        /// Therefore we rely here on 3rd party library: https://github.com/icsharpcode/SharpZipLib
        /// </remarks>
        private bool TryExtractToDisk(DownloadData downloadData)
        {
            var archive = downloadData.DownloadedFilePath.ToString(m_context.PathTable);
            var target  = downloadData.ContentsFolder.Path.ToString(m_context.PathTable);

            try
            {
                FileUtilities.DeleteDirectoryContents(target, false);
                FileUtilities.CreateDirectory(target);
            }
            catch (BuildXLException e)
            {
                m_logger.ErrorExtractingArchive(m_context.LoggingContext, downloadData.Settings.ModuleName, archive, target, e.Message);
                return(false);
            }

            switch (downloadData.Settings.ArchiveType)
            {
            case DownloadArchiveType.Zip:
                try
                {
                    new FastZip().ExtractZip(archive, target, null);
                }
                catch (ZipException e)
                {
                    m_logger.ErrorExtractingArchive(m_context.LoggingContext, downloadData.Settings.ModuleName, archive, target, e.Message);
                    return(false);
                }

                break;

            case DownloadArchiveType.Gzip:
                try
                {
                    var targetFile = Path.Combine(
                        target,
                        downloadData.DownloadedFilePath.GetName(m_context.PathTable).RemoveExtension(m_context.StringTable)
                        .ToString(m_context.StringTable));

                    using (var reader = m_context.FileSystem.OpenText(downloadData.DownloadedFilePath))
                        using (var gzipStream = new GZipInputStream(reader.BaseStream))
                            using (var output = FileUtilities.CreateFileStream(targetFile, FileMode.Create, FileAccess.Write, FileShare.Read))
                            {
                                byte[] buffer = new byte[4096];
                                StreamUtils.Copy(gzipStream, output, buffer);
                            }
                }
                catch (GZipException e)
                {
                    m_logger.ErrorExtractingArchive(m_context.LoggingContext, downloadData.Settings.ModuleName, archive, target, e.Message);
                    return(false);
                }

                break;

            case DownloadArchiveType.Tar:
                try
                {
                    using (var reader = m_context.FileSystem.OpenText(downloadData.DownloadedFilePath))
                        using (var tar = TarArchive.CreateInputTarArchive(reader.BaseStream))
                        {
                            tar.ExtractContents(target);
                        }
                }
                catch (TarException e)
                {
                    m_logger.ErrorExtractingArchive(m_context.LoggingContext, downloadData.Settings.ModuleName, archive, target, e.Message);
                    return(false);
                }

                break;

            case DownloadArchiveType.Tgz:
                try
                {
                    using (var reader = m_context.FileSystem.OpenText(downloadData.DownloadedFilePath))
                        using (var gzipStream = new GZipInputStream(reader.BaseStream))
                            using (var tar = TarArchive.CreateInputTarArchive(gzipStream))
                            {
                                tar.ExtractContents(target);
                            }
                }
                catch (GZipException e)
                {
                    m_logger.ErrorExtractingArchive(m_context.LoggingContext, downloadData.Settings.ModuleName, archive, target, e.Message);
                    return(false);
                }
                catch (TarException e)
                {
                    m_logger.ErrorExtractingArchive(m_context.LoggingContext, downloadData.Settings.ModuleName, archive, target, e.Message);
                    return(false);
                }

                break;

            default:
                throw Contract.AssertFailure("Unexpected archive type");
            }

            try
            {
                if (!FileUtilities.DirectoryExistsNoFollow(target))
                {
                    m_logger.ErrorNothingExtracted(m_context.LoggingContext, downloadData.Settings.ModuleName, archive, target);
                    return(false);
                }
            }
            catch (BuildXLException e)
            {
                m_logger.ErrorExtractingArchive(m_context.LoggingContext, downloadData.Settings.ModuleName, archive, target, e.Message);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 24
0
        public string getZipFile(string filedata, string customer, string judge)
        {
            string dir     = @"d:/ftpserver/";
            string tmp_dir = @"d:/ftpserver/declare_tmp_zip/";

            if (!Directory.Exists(tmp_dir))
            {
                Directory.CreateDirectory(tmp_dir);
            }
            try
            {
                JArray j_array = JArray.Parse(filedata);

                string codelist = "(";
                int    i        = 0;
                foreach (JObject jo in j_array)
                {
                    codelist += "'" + jo["CODE"] + "'";
                    if (i != j_array.Count - 1)
                    {
                        codelist += ",";
                    }
                    i++;
                }
                codelist += ")";

                string    sql = @"select t.* from list_attachment t where t.filetype='61' and t.declcode in " + codelist + " order by pgindex asc,uploadtime asc";
                DataTable dt  = DBMgr.GetDataTable(sql);


                string filepath = string.Empty;
                //MemoryStream ms = new MemoryStream();
                ZipEntryFactory zipEntryFactory = new ZipEntryFactory();
                //ZipFile zipFile = new ZipFile(ms);
                string filename      = DateTime.Now.ToString("yyyyMMddhhmmssff") + ".zip";
                string newfilename   = string.Empty;
                string sourcefile    = string.Empty;
                string filepath_mask = string.Empty;
                string busitype      = string.Empty;
                using (ZipOutputStream outPutStream = new ZipOutputStream(System.IO.File.Create(tmp_dir + filename)))
                {
                    outPutStream.SetLevel(5);
                    ZipEntry entry  = null;
                    byte[]   buffer = null;
                    //foreach (DataRow dr in dt.Rows)
                    foreach (JObject jo in j_array)
                    {
                        DataRow[] drs = dt.Select("DECLCODE='" + jo["CODE"] + "'");
                        busitype   = jo["BUSITYPE"].ToString();
                        sourcefile = drs[0]["FILENAME"].ToString();
                        filepath   = dir + sourcefile;



                        filepath_mask = AddBackground(filepath, "企业留存联", busitype, "", customer, judge);



                        newfilename = jo["DECLARATIONCODE"].ToString() + sourcefile.Substring(sourcefile.LastIndexOf("."));
                        buffer      = new byte[4096];
                        entry       = zipEntryFactory.MakeFileEntry(newfilename);
                        outPutStream.PutNextEntry(entry);
                        using (FileStream fileStream = File.OpenRead(filepath_mask))
                        {
                            StreamUtils.Copy(fileStream, outPutStream, buffer);
                        }
                    }
                    outPutStream.Finish();
                    outPutStream.Close();
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();

                return("/file/declare_tmp_zip/" + filename);
            }
            catch (Exception)
            {
                return("error");
            }
        }
Ejemplo n.º 25
0
        public static void ExtractArchive(string archivePath, string destinationDirectory, CancellationTokenEx cancellationToken,
                                          ReportCompressionStatus reportCompressionStatus, AddProcessingEntry addProcessingEntry)
        {
            bool   isTar;
            Stream inputStream = new FileStream(archivePath, FileMode.Open, FileAccess.Read);

            switch (Path.GetExtension(archivePath).ToUpper())
            {
            case ".ZIP":
                var fastZip = new FastZip();
                fastZip.ExtractZip(inputStream, destinationDirectory, FastZip.Overwrite.Always, null, null, null,
                                   true, true);
                //TODO: Add progress
                return;

            case ".TAR":
                isTar = true;
                break;

            case ".GZ":
                inputStream = new GZipInputStream(inputStream)
                {
                    IsStreamOwner = true
                };
                isTar = archivePath.EndsWith(".tar.gz", StringComparison.OrdinalIgnoreCase);
                break;

            case ".BZ2":
                inputStream = new BZip2InputStream(inputStream)
                {
                    IsStreamOwner = true
                };
                isTar = archivePath.EndsWith(".tar.bz2", StringComparison.OrdinalIgnoreCase);
                break;

            case ".LZW":
                inputStream = new LzwInputStream(inputStream)
                {
                    IsStreamOwner = true
                };
                isTar = archivePath.EndsWith(".tar.lzw", StringComparison.OrdinalIgnoreCase);
                break;

            default:
                inputStream.Dispose();
                return;
            }

            Directory.CreateDirectory(destinationDirectory);

            using (inputStream)
            {
                if (isTar)
                {
                    using (TarArchive tarArchive = TarArchive.CreateInputTarArchive(inputStream))
                    {
                        TarEntry        lastEntry           = null;
                        ProcessingEntry lastProcessingEntry = null;

                        tarArchive.ProgressMessageEvent += (archive, entry, message) =>
                        {
                            if (lastEntry != entry)
                            {
                                if (lastEntry != null)
                                {
                                    lastProcessingEntry.Progress = 1;
                                    lastProcessingEntry.Size     = entry.Size;
                                    ThreadPool.QueueUserWorkItem(state => reportCompressionStatus(lastProcessingEntry));
                                }

                                lastEntry           = entry;
                                lastProcessingEntry = new ProcessingEntry
                                {
                                    Action       = ProcessingEntryAction.Extracting,
                                    CreationTime = DateTime.UtcNow,
                                    Path         = entry.File,
                                    Progress     = 0,
                                    Name         = entry.Name
                                };
                                ThreadPool.QueueUserWorkItem(state => addProcessingEntry(lastProcessingEntry));
                            }
                        };
                        tarArchive.ExtractContents(destinationDirectory);
                    }
                }
                else
                {
                    var filename            = Path.GetFileNameWithoutExtension(archivePath);
                    var destinationFilePath = Path.Combine(destinationDirectory, filename);

                    var processingEntry = new ProcessingEntry
                    {
                        Action        = ProcessingEntryAction.Extracting,
                        CreationTime  = DateTime.UtcNow,
                        IsDirectory   = false,
                        IsInterminate = false,
                        LastAccess    = DateTime.UtcNow,
                        Path          = destinationFilePath,
                        Name          = filename
                    };

                    byte[] dataBuffer = new byte[4096];
                    using (var destinationFileStream = new FileStream(destinationFilePath, FileMode.Create, FileAccess.ReadWrite))
                    {
                        addProcessingEntry(processingEntry);

                        StreamUtils.Copy(inputStream, destinationFileStream, dataBuffer, (sender, args) =>
                        {
                            processingEntry.Progress = args.PercentComplete / 100;
                            processingEntry.Size     = destinationFileStream.Length;
                            args.ContinueRunning     = !cancellationToken.IsCanceled;
                            ThreadPool.QueueUserWorkItem(state => reportCompressionStatus.Invoke(processingEntry));
                        },
                                         TimeSpan.FromSeconds(1), null, null);

                        if (cancellationToken.IsCanceled)
                        {
                            processingEntry.Progress = -1;
                            ThreadPool.QueueUserWorkItem(state => reportCompressionStatus.Invoke(processingEntry));
                            return;
                        }

                        processingEntry.Progress = 1;
                        processingEntry.Size     = destinationFileStream.Length;
                        ThreadPool.QueueUserWorkItem(state => reportCompressionStatus.Invoke(processingEntry));
                    }
                }
            }
        }
Ejemplo n.º 26
0
        } // End UnZip

        /// <summary>
        /// Unzip a local file and return its contents via streamreader to a local the same location as the ZIP.
        /// </summary>
        /// <param name="zipFile">Location of the zip on the HD</param>
        /// <returns>List of unzipped file names</returns>
        public static List <string> UnzipToFolder(string zipFile)
        {
            //1. Initialize:
            var files     = new List <string>();
            var outFolder = Path.GetDirectoryName(zipFile);

            if (string.IsNullOrEmpty(outFolder))
            {
                outFolder = Directory.GetCurrentDirectory();
            }
            ICSharpCode.SharpZipLib.Zip.ZipFile zf = null;

            try
            {
                var fs = File.OpenRead(zipFile);
                zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(fs);

                foreach (ZipEntry zipEntry in zf)
                {
                    //Ignore Directories
                    if (!zipEntry.IsFile)
                    {
                        continue;
                    }

                    var buffer    = new byte[4096]; // 4K is optimum
                    var zipStream = zf.GetInputStream(zipEntry);

                    // Manipulate the output filename here as desired.
                    var fullZipToPath = Path.Combine(outFolder, zipEntry.Name);

                    var targetFile = new FileInfo(fullZipToPath);
                    if (targetFile.Directory != null && !targetFile.Directory.Exists)
                    {
                        targetFile.Directory.Create();
                    }

                    //Save the file name for later:
                    files.Add(fullZipToPath);

                    //Copy the data in buffer chunks
                    using (var streamWriter = File.Create(fullZipToPath))
                    {
                        StreamUtils.Copy(zipStream, streamWriter, buffer);
                    }
                }
            }
            catch
            {
                // lets catch the exception just to log some information about the zip file
                Log.Error($"Compression.UnzipToFolder(): Failure: zipFile: {zipFile} - outFolder: {outFolder} - files: {string.Join(",", files)}");
                throw;
            }
            finally
            {
                if (zf != null)
                {
                    zf.IsStreamOwner = true; // Makes close also shut the underlying stream
                    zf.Close();              // Ensure we release resources
                }
            }
            return(files);
        } // End UnZip
Ejemplo n.º 27
0
        public void writeKMLFirstPerson(string filename)
        {
            StreamWriter stream = new StreamWriter(File.Open(filename, FileMode.Create));

            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            string header = "<?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\">\n     <Document>   <name>Paths</name>    <description>Path</description>\n    <Style id=\"yellowLineGreenPoly\">      <LineStyle>        <color>7f00ffff</color>        <width>4</width>      </LineStyle>      <PolyStyle>        <color>7f00ff00</color>      </PolyStyle>    </Style>\n  ";

            stream.Write(header);

            StringBuilder kml  = new StringBuilder();
            StringBuilder data = new StringBuilder();

            double lastlat       = 0;
            double lastlong      = 0;
            int    gpspackets    = 0;
            int    lastgpspacket = 0;

            foreach (Data mod in flightdata)
            {
                if (mod.model.Location.latitude == 0)
                {
                    continue;
                }

                gpspackets++;
                if (lastlat == mod.model.Location.latitude && lastlong == mod.model.Location.longitude)
                {
                    continue;
                }
                // double speed 0.05 - assumeing 10hz in log file
                // 1 speed = 0.1    10 / 1  = 0.1
                data.Append(@"
        <gx:FlyTo>
            <gx:duration>" + ((gpspackets - lastgpspacket) * 0.1) + @"</gx:duration>
            <gx:flyToMode>smooth</gx:flyToMode>
            <Camera>
                <longitude>" + mod.model.Location.longitude.ToString(new System.Globalization.CultureInfo("en-US")) + @"</longitude>
                <latitude>" + mod.model.Location.latitude.ToString(new System.Globalization.CultureInfo("en-US")) + @"</latitude>
                <altitude>" + mod.model.Location.altitude.ToString(new System.Globalization.CultureInfo("en-US")) + @"</altitude>
                <roll>" + mod.model.Orientation.roll.ToString(new System.Globalization.CultureInfo("en-US")) + @"</roll>
                <tilt>" + (90 - mod.model.Orientation.tilt).ToString(new System.Globalization.CultureInfo("en-US")) + @"</tilt>
                <heading>" + mod.model.Orientation.heading.ToString(new System.Globalization.CultureInfo("en-US")) + @"</heading>              
                <altitudeMode>absolute</altitudeMode>
            </Camera>
        </gx:FlyTo>
");
                lastlat       = mod.model.Location.latitude;
                lastlong      = mod.model.Location.longitude;
                lastgpspacket = gpspackets;
            }

            kml.Append(@"
        <Folder>
            <name>Flight</name> 
            <gx:Tour>
                <name>Flight Do</name> 
                <gx:Playlist>
                    " + data +
                       @"</gx:Playlist> 
            </gx:Tour>
        </Folder>
    </Document>
</kml>
");

            stream.Write(kml.ToString());
            stream.Close();

            // create kmz - aka zip file

            FileStream      fs        = File.Open(filename.Replace(".log-fp.kml", "-fp.kmz"), FileMode.Create);
            ZipOutputStream zipStream = new ZipOutputStream(fs);

            zipStream.SetLevel(9);             //0-9, 9 being the highest level of compression
            zipStream.UseZip64 = UseZip64.Off; // older zipfile

            // entry 1
            string   entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction
            ZipEntry newEntry  = new ZipEntry(entryName);

            newEntry.DateTime = DateTime.Now;

            zipStream.PutNextEntry(newEntry);

            // Zip the file in buffered chunks
            // the "using" will close the stream even if an exception occurs
            byte[] buffer = new byte[4096];
            using (FileStream streamReader = File.OpenRead(filename))
            {
                StreamUtils.Copy(streamReader, zipStream, buffer);
            }
            zipStream.CloseEntry();

            File.Delete(filename);

            filename = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "block_plane_0.dae";

            // entry 2
            entryName         = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction
            newEntry          = new ZipEntry(entryName);
            newEntry.DateTime = DateTime.Now;

            zipStream.PutNextEntry(newEntry);

            // Zip the file in buffered chunks
            // the "using" will close the stream even if an exception occurs
            buffer = new byte[4096];
            using (FileStream streamReader = File.OpenRead(filename))
            {
                StreamUtils.Copy(streamReader, zipStream, buffer);
            }
            zipStream.CloseEntry();


            zipStream.IsStreamOwner = true;     // Makes the Close also Close the underlying stream
            zipStream.Close();

            positionindex = 0;
            modelist.Clear();
            flightdata.Clear();
            position = new List <Core.Geometry.Point3D> [200];
            cmd.Clear();
        }
Ejemplo n.º 28
0
        public async Task DownloadModuleAsync(string moduleName, string outputFolder, string version, string gitHubAbpLocalRepositoryPath, string gitHubVoloLocalRepositoryPath, AbpCommandLineOptions options)
        {
            Logger.LogInformation("Downloading source code of " + moduleName);
            Logger.LogInformation("Version: " + version);
            Logger.LogInformation("Output folder: " + outputFolder);

            var result = await ModuleProjectBuilder.BuildAsync(
                new ProjectBuildArgs(
                    SolutionName.Parse(moduleName),
                    moduleName,
                    version,
                    outputFolder,
                    DatabaseProvider.NotSpecified,
                    DatabaseManagementSystem.NotSpecified,
                    UiFramework.NotSpecified,
                    null,
                    false,
                    gitHubAbpLocalRepositoryPath,
                    gitHubVoloLocalRepositoryPath,
                    null,
                    options
                    )
                );

            using (var templateFileStream = new MemoryStream(result.ZipContent))
            {
                using (var zipInputStream = new ZipInputStream(templateFileStream))
                {
                    var zipEntry = zipInputStream.GetNextEntry();
                    while (zipEntry != null)
                    {
                        if (IsAngularTestFile(zipEntry.Name))
                        {
                            zipEntry = zipInputStream.GetNextEntry();
                            continue;
                        }

                        var fullZipToPath = Path.Combine(outputFolder, zipEntry.Name);
                        var directoryName = Path.GetDirectoryName(fullZipToPath);

                        if (!string.IsNullOrEmpty(directoryName))
                        {
                            Directory.CreateDirectory(directoryName);
                        }

                        var fileName = Path.GetFileName(fullZipToPath);
                        if (fileName.Length == 0)
                        {
                            zipEntry = zipInputStream.GetNextEntry();
                            continue;
                        }

                        var buffer = new byte[4096]; // 4K is optimum
                        using (var streamWriter = File.Create(fullZipToPath))
                        {
                            StreamUtils.Copy(zipInputStream, streamWriter, buffer);
                        }

                        zipEntry = zipInputStream.GetNextEntry();
                    }
                }
            }

            Logger.LogInformation($"'{moduleName}' has been successfully downloaded to '{outputFolder}'");
        }
Ejemplo n.º 29
0
        void ExtractFileEntry(ZipEntry entry, string targetName)
        {
            bool proceed = true;

            if (overwrite_ != Overwrite.Always)
            {
                if (File.Exists(targetName))
                {
                    if ((overwrite_ == Overwrite.Prompt) && (confirmDelegate_ != null))
                    {
                        proceed = confirmDelegate_(targetName);
                    }
                    else
                    {
                        proceed = false;
                    }
                }
            }

            if (proceed)
            {
                if (events_ != null)
                {
                    continueRunning_ = events_.OnProcessFile(entry.Name);
                }

                if (continueRunning_)
                {
                    try
                    {
                        using (FileStream outputStream = File.Create(targetName))
                        {
                            if (buffer_ == null)
                            {
                                buffer_ = new byte[4096];
                            }
                            if ((events_ != null) && (events_.Progress != null))
                            {
                                StreamUtils.Copy(zipFile_.GetInputStream(entry), outputStream, buffer_,
                                                 events_.Progress, events_.ProgressInterval, this, entry.Name, entry.Size);
                            }
                            else
                            {
                                StreamUtils.Copy(zipFile_.GetInputStream(entry), outputStream, buffer_);
                            }

                            if (events_ != null)
                            {
                                continueRunning_ = events_.OnCompletedFile(entry.Name);
                            }
                        }

#if !NETCF_1_0 && !NETCF_2_0
                        if (restoreDateTimeOnExtract_)
                        {
                            File.SetLastWriteTime(targetName, entry.DateTime);
                        }

                        if (RestoreAttributesOnExtract && entry.IsDOSEntry && (entry.ExternalFileAttributes != -1))
                        {
                            FileAttributes fileAttributes = (FileAttributes)entry.ExternalFileAttributes;
                            // TODO: FastZip - Setting of other file attributes on extraction is a little trickier.
                            fileAttributes &= (FileAttributes.Archive | FileAttributes.Normal | FileAttributes.ReadOnly | FileAttributes.Hidden);
                            File.SetAttributes(targetName, fileAttributes);
                        }
#endif
                    }
                    catch (Exception ex)
                    {
                        if (events_ != null)
                        {
                            continueRunning_ = events_.OnFileFailure(targetName, ex);
                        }
                        else
                        {
                            continueRunning_ = false;
                            throw;
                        }
                    }
                }
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Patches the given minecraft version and returns the new patched version.
        /// The patcher will create a new version directory and create a new jar file.
        /// The jar file is based on the original <paramref name="version"/>.
        /// The patcher will copy any assets from the orignal jar file.
        /// The content of the META-INF directory will not be copied.
        /// All classes will be analysed and scanned for a keyPressed method.
        /// The patcher will replace 0x110102 from the keyPressed methods.
        /// 0x11 (sipush) is the java bytecode instruction that loads the next two
        /// bytes as short value onto the stack. Where 0x0102 is the short value for
        /// 258 which is the minecraft keycode for tab. 0x0102 will be replaced with
        /// 0xFFFF which is an invalid keycode.
        /// </summary>
        /// <param name="version"></param>
        /// <param name="postfix"></param>
        /// <returns></returns>
        private static MinecraftVersion Patch(MinecraftVersion version, string postfix)
        {
            Console.WriteLine("Start pathching '{0}'...", version.ID);
            Console.WriteLine("------------------------------------------------------");

            // Creates a new version
            var parentPath = Path.GetDirectoryName(version.Path);

            // Searches for the next free directory.
            // Is this really necessary?
            var template = version.ID + "-" + postfix;
            var id       = template;
            var path     = Path.Combine(parentPath, id);
            var counter  = 1;

            while (Directory.Exists(path))
            {
                counter++;
                id   = template + counter;
                path = Path.Combine(parentPath, id);
            }

            Console.WriteLine("Creating patched version '{0}'...", id);

            // Creates the patched version
            var patchedVersion = new MinecraftVersion(path);

            // The copy buffer
            var buffer = new byte[1024 * 8];

            // Opens the java file
            using (var javaFile = version.OpenJavaFile())
            {
                // Creates the output file
                using (var output = new FileStream(patchedVersion.PathJar, FileMode.Create))
                {
                    // Creates the output zip stream
                    using (var outputZip = new ZipOutputStream(output))
                    {
                        // Do not use 64 bit zip
                        outputZip.UseZip64 = UseZip64.Off;

                        var files = javaFile.Zip.Count;
                        for (int i = 0; i < files; i++)
                        {
                            var entry = javaFile.Zip[i];


                            // Ignore the META-INF folder
                            if (entry.Name.Contains("META-INF/"))
                            {
                                continue;
                            }

                            // Creates the output entry file
                            var outputEntry = new ZipEntry(entry.Name);
                            outputEntry.DateTime = entry.DateTime;
                            outputEntry.Size     = entry.Size;
                            outputZip.PutNextEntry(outputEntry);

                            // This is a class file
                            if (Path.GetExtension(entry.Name) == ".class")
                            {
                                // Loads the class
                                var javaClass = javaFile.GetClass(entry);

                                // Gets the class info
                                var javaClassInfo = javaClass.GetConstant <JavaConstantClassInfo>(javaClass.ThisClass);
                                var javaClassName = javaClass.GetConstantUtf8(javaClassInfo.NameIndex);

                                // Gets the method
                                var javaMethod = javaClass.GetMethod("keyPressed");


                                if (javaMethod != null)
                                {
                                    // Gets the method info
                                    var javaMethodName       = javaClass.GetConstantUtf8(javaMethod.NameIndex);
                                    var javaMethodDescriptor = javaClass.GetConstantUtf8(javaMethod.DescriptorIndex);

                                    // Gets the code attribute of the method
                                    var javaCodeAttribute = javaMethod.GetCodeAttribute();
                                    if (javaCodeAttribute != null)
                                    {
                                        var code  = javaCodeAttribute.Code;
                                        var index = 0;
                                        while ((index = Utils.BinaryIndexOf(code, OrginalCode, index)) >= 0)
                                        {
                                            Console.WriteLine("Patching bytecode from '{0}.{1}{2}' at position {3}...", javaClassName, javaMethodName, javaMethodDescriptor, index);

                                            // Change the code
                                            code[index + 1] = 0xFF;
                                            code[index + 2] = 0xFF;


                                            index++;
                                        }
                                    }
                                }

                                // Writes the class
                                javaClass.Write(outputZip);
                            }
                            else
                            {
                                // Just copy the file
                                using (var inputStream = javaFile.GetFileStream(entry))
                                {
                                    StreamUtils.Copy(inputStream, outputZip, buffer);
                                }
                            }
                        }
                    }
                }
            }

            Console.WriteLine("Creating json file...");

            // Creates the json file
            var patchedInfo = new MinecraftVersionInfo()
            {
                ID                     = id,
                InheritsFrom           = version.ID,
                Type                   = "custom",
                MainClass              = "net.minecraft.client.main.Main",
                MinimumLauncherVersion = 21,
            };

            // Write the version json
            patchedVersion.WriteJsonFile(patchedInfo);

            Console.WriteLine("Version got patched!");

            return(patchedVersion);
        }