Esempio n. 1
0
        static void Main(string[] args)
        {
            var zipService = new ZipService(new AzureStorageRepository());

            Console.WriteLine("1-Upload");
            Console.WriteLine("2-Download");

            int x = int.Parse(Console.ReadKey().KeyChar.ToString());

            switch (x)
            {
            case 1:
                OpenFileDialog dialog = new OpenFileDialog();
                string         path   = string.Empty;

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    path = dialog.FileName;
                }

                List <PreZipEntryModel> collection = new List <PreZipEntryModel>();

                FileStream reader = new FileStream(path, FileMode.Open);

                collection.Add(new PreZipEntryModel(reader));

                zipService.UploadFile(collection);
                break;

            case 2:
                zipService.OpenZip();
                break;
            }
        }
Esempio n. 2
0
        public static void DllToModule(string DllName, ref byte[] DllData)
        {
            Console.WriteLine("Insert RC4 Key for {0}:", DllName);
            string RC4Key = Console.ReadLine();
            var    Key    = Program.ParseKey(RC4Key);

            Key = Program.RC4.Init(Key);
            var CompressedData = new ZipService().Compress(DllData, 0, DllData.Length);
            var mw             = new MemoryStream();
            var bw             = new BinaryWriter(mw);

            bw.Write(DllData.Length);                           // Uncompressed buffer
            bw.Write(CompressedData, 0, CompressedData.Length); // Data
            bw.Write((byte)Strings.Asc('N'));                   // \
            bw.Write((byte)Strings.Asc('G'));                   // \ Sign
            bw.Write((byte)Strings.Asc('I'));                   // /
            bw.Write((byte)Strings.Asc('S'));                   // /
            var tmpData   = mw.ToArray();
            var Signature = CreateSignature(tmpData, tmpData.Length - 4);

            bw.Write(Signature, 0, Signature.Length);
            tmpData = mw.ToArray();
            mw.Close();
            mw.Dispose();
            Program.RC4.Crypt(ref tmpData, Key);
            var fs2 = new FileStream(@"Modules\" + DllName.Replace(Path.GetExtension(DllName), "") + ".mod", FileMode.Create, FileAccess.Write, FileShare.None);

            fs2.Write(tmpData, 0, tmpData.Length);
            fs2.Close();
            fs2.Dispose();
        }
Esempio n. 3
0
        public async Task LaunchPlayer(Core.Models.Program program, bool isLaunchedFromTile)
        {
            await ShowSplashScreen(program.Name);

            var zipService = new ZipService();
            var tempFolder = ApplicationData.Current.TemporaryFolder;
            var file       = await tempFolder.CreateFileAsync(TempProgramName,
                                                              CreationCollisionOption.ReplaceExisting);

            var stream = await file.OpenStreamForWriteAsync();

            await zipService.ZipCatrobatPackage(stream, program.BasePath);

            var options = new Windows.System.LauncherOptions {
                DisplayApplicationPicker = false
            };

            //await project.Save(); ??? TODO: this was in the previous version of catrobat --> do we need to save the project at this point?
            await LaunchPlayer(program.Name, isLaunchedFromTile);

            // TODO: manage closing/relaunching of the Player
            // TODO: review ...LaunchFileAsync (1 line underneath) --> seems to be that it never finishes
            //bool success = await Windows.System.Launcher.LaunchFileAsync(file, options);
            //if (success)
            //{
            //    // File launch success
            //}
            //else
            //{
            //    // File launch failed
            //}
        }
Esempio n. 4
0
        public ActionResult Index(HomeViewModel model)
        {
            var zipService = new ZipService();

            List <SelectListItem> countyList = GetCountySelectList(model.SelectedCounties);

            model.CountySelectList = new MultiSelectList(countyList, "Value", "Text");

            var excludeList = new List <string>();

            if (model.ExcludedZips != null)
            {
                excludeList = new List <string>(model.ExcludedZips.Split(new char[] { ',' }));
            }

            var includeList = new List <string>();

            if (model.IncludeZips != null)
            {
                includeList = new List <string>(model.IncludeZips.Split(new char[] { ',' }));
            }

            if (model.SelectedCounties != null)
            {
                var zipsFound = zipService.GetZips(model.SelectedCounties, excludeList, includeList);
                model.GeneratedZips = string.Join(System.Environment.NewLine, zipsFound);
            }

            return(View(model));
        }
Esempio n. 5
0
        public static void ModuleToDll(string ModName, ref byte[] ModData)
        {
            // Console.WriteLine("Insert RC4 Key for {0}:", ModName)
            // Dim RC4Key As String = Console.ReadLine()

            var Key = Program.ParseKey("ECA9A9D1EAAEFD38CC115062FB92996E"); // ParseKey(RC4Key)

            Key = Program.RC4.Init(Key);
            Program.RC4.Crypt(ref ModData, Key);
            int UncompressedLen = BitConverter.ToInt32(ModData, 0);

            if (UncompressedLen < 0)
            {
                Console.WriteLine("Failed to decrypt {0}, incorrect length.", ModName);
                return;
            }

            var CompressedData = new byte[(ModData.Length - 0x108)];

            Array.Copy(ModData, 4, CompressedData, 0, CompressedData.Length);
            int    dataPos = 4 + CompressedData.Length;
            string Sign    = Conversions.ToString((char)ModData[dataPos + 3]) + (char)ModData[dataPos + 2] + (char)ModData[dataPos + 1] + (char)ModData[dataPos];

            if (Sign != "SIGN")
            {
                Console.WriteLine("Failed to decrypt {0}, sign missing.", ModName);
                return;
            }

            dataPos += 4;
            var Signature = new byte[256];

            Array.Copy(ModData, dataPos, Signature, 0, Signature.Length);

            // Check signature
            if (CheckSignature(Signature, ModData, ModData.Length - 0x104) == false)
            {
                Console.WriteLine("Signature fail.");
                return;
            }

            var DecompressedData = new ZipService().DeCompress(CompressedData);
            var fs3 = new FileStream(@"dlls\" + ModName.Replace(Path.GetExtension(ModName), "") + ".before.dll", FileMode.Create, FileAccess.Write, FileShare.None);

            fs3.Write(DecompressedData, 0, DecompressedData.Length);
            fs3.Close();
            fs3.Dispose();
            Module_FixDll.FixNormalDll(ref DecompressedData);
            var fs2 = new FileStream(@"dlls\" + ModName.Replace(Path.GetExtension(ModName), "") + ".after.dll", FileMode.Create, FileAccess.Write, FileShare.None);

            fs2.Write(DecompressedData, 0, DecompressedData.Length);
            fs2.Close();
            fs2.Dispose();
        }
Esempio n. 6
0
        public void GetZipsByStateReturnsZipsWithStateCodeMatchingAbbreviation()
        {
            var mockZipRepository = new Mock <IRepository <ZipCode> >();

            mockZipRepository.Setup(mock => mock.Get()).Returns(_mockData.GetZipCodes);
            ZipService service  = new ZipService(mockZipRepository.Object);
            var        zipCodes = service.GetZipsByState("AK");

            Assert.That(zipCodes.Count, Is.EqualTo(3));
            Assert.That(zipCodes.Select(zip => zip.StateName).ToArray(), Has.All.Contains("Alaska"));
        }
        static void Main(string[] args)
        {
            var baseCulture   = "english";
            var targetCulture = "german";

            if (args.Length >= 1)
            {
                baseCulture = args[0];
            }

            if (args.Length >= 2)
            {
                targetCulture = args[1];
            }

            var basePath = ".";

            if (args.Length >= 3)
            {
                basePath = args[2];
            }

            var modRepository = new ModRepository(@basePath);

            var modsWithoutGerman = modRepository
                                    .GetAllMods()
                                    .Where(it =>
                                           it.LocalizationFiles.Count > 0 &&
                                           !it.LocalizationFiles.Any(lf =>
                                                                     lf.FileName.Contains(targetCulture, StringComparison.OrdinalIgnoreCase)));

            var zip = new ZipService();

            foreach (var mod in modsWithoutGerman)
            {
                System.Console.WriteLine("--------------");
                System.Console.WriteLine($"{mod.ID} - {mod.Name}");
                foreach (var localizationFile in mod.LocalizationFiles)
                {
                    System.Console.WriteLine($"\t{localizationFile.FileName}");
                }

                var tempFolder = Path.Combine(Path.GetDirectoryName(mod.Location), "temp");
                zip.Extract(mod.Location, tempFolder);
                new TranslationService().Multiply(tempFolder, baseCulture, new [] { targetCulture });
                zip.Compress(tempFolder, mod.Location, ZipService.CompressMode.Backup);

                Directory.Delete(tempFolder, true);
                System.Console.WriteLine("--------------");
            }
        }
Esempio n. 8
0
            /* TODO ERROR: Skipped RegionDirectiveTrivia */
            public bool LoadModule(string Name, ref byte[] Data, byte[] Key)
            {
                Key = RC4.Init(Key);
                RC4.Crypt(ref Data, Key);
                int UncompressedLen = BitConverter.ToInt32(Data, 0);

                if (UncompressedLen < 0)
                {
                    Console.WriteLine("[WARDEN] Failed to decrypt {0}, incorrect length.", Name);
                    return(false);
                }

                var CompressedData = new byte[(Data.Length - 0x108)];

                Array.Copy(Data, 4, CompressedData, 0, CompressedData.Length);
                int    dataPos = 4 + CompressedData.Length;
                string Sign    = Conversions.ToString((char)Data[dataPos + 3]) + (char)Data[dataPos + 2] + (char)Data[dataPos + 1] + (char)Data[dataPos];

                if (Sign != "SIGN")
                {
                    Console.WriteLine("[WARDEN] Failed to decrypt {0}, sign missing.", Name);
                    return(false);
                }

                dataPos += 4;
                var Signature = new byte[256];

                Array.Copy(Data, dataPos, Signature, 0, Signature.Length);

                // Check signature
                if (CheckSignature(Signature, Data, Data.Length - 0x104) == false)
                {
                    Console.WriteLine("[WARDEN] Signature fail on Warden Module.");
                    return(false);
                }

                var DecompressedData = new ZipService().DeCompress(CompressedData);
                var ms = new MemoryStream(DecompressedData);
                var br = new BinaryReader(ms);

                ModuleData = PrepairModule(ref br);
                ms.Close();
                ms.Dispose();
                br = null;
                Console.WriteLine("[WARDEN] Successfully prepaired Warden Module.");
                if (!InitModule(ref ModuleData))
                {
                    return(false);
                }
                return(true);
            }
Esempio n. 9
0
        public async Task ExtractFileTest()
        {
            var path     = "Assets/file.zip";
            var expected = "text";
            var service  = new ZipService();

            var target = service.ExtractZip(path);

            Assert.NotNull(target);
            Assert.True(File.Exists(target));
            var content = await File.ReadAllTextAsync(target);

            Assert.Equal(expected, content);
        }
Esempio n. 10
0
        private byte[] GenerateReport(TestClassReport report)
        {
            var zipService = new ZipService();

            var templateFolder      = string.Format("{0}/Templates/{1}", Directory.GetCurrentDirectory(), ThemeFolder);
            var templateFileContent = File.ReadAllText(string.Format("{0}/{1}", templateFolder, ThemeTemplateFileName));

            var renderedResult        = Razor.Parse(templateFileContent, report);
            var renderedResultContent = System.Text.Encoding.UTF8.GetBytes(renderedResult);

            var renderedZipItem = new ZipService.ZipItem
            {
                Name    = "index.html",
                Content = renderedResultContent
            };

            var zipArchive = zipService.Zip(templateFolder, new ZipService.ZipItem[] { renderedZipItem });

            return(ZipService.ReadToEnd(zipArchive));
        }
        public void LoadTest()
        {
            OpenFileDialog dialog = new OpenFileDialog();
            var            path   = @"C:\Users\pavel_petrusevich\Desktop\download.jpg";

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                path = dialog.FileName;
            }

            var zipService = new ZipService(new AzureStorageRepository());

            List <PreZipEntryModel> collection = new List <PreZipEntryModel>();

            FileStream reader = new FileStream(path, FileMode.Open);

            collection.Add(new PreZipEntryModel(reader));

            zipService.UploadFile(collection);

            reader.Close();
        }
        private void DownloadAndExtractVersion(GodotVersion selectedVersion)
        {
            string fileName;

            try
            {
                fileName = config.UseProxy ? DownloadManagerService.DownloadFileSyncWithProxy(selectedVersion.VersionUrl, "temp", config.ProxyUrl, config.ProxyPort, true) :
                           DownloadManagerService.DownloadFileSync(selectedVersion.VersionUrl, "temp", true);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            var extractedFiles = ZipService.UnzipFile(fileName, $"{config.GodotInstallLocation}\\{selectedVersion.VersionName}");

            File.Delete(fileName);

            foreach (var file in extractedFiles)
            {
                versionService.InstalledVersions.Add(new GodotVersionInstalled
                {
                    VersionId   = selectedVersion.VersionId,
                    VersionName = selectedVersion.VersionName,
                    BitNum      = selectedVersion.BitNum,
                    IsMono      = selectedVersion.IsMono,
                    IsStable    = selectedVersion.IsStable,
                    InstallPath = file.Replace(@"/", @"\\"),
                });
            }

            JsonConverterService <List <GodotVersionInstalled> > .Serialize(versionService.InstalledVersions, $"{config.GodotInstallLocation}\\manifest.json");

            Dispatcher.Invoke(new Action(() => BuildVersionsTree()));

            Dispatcher.Invoke(new Action(() => CommonUtilsService.PopupInfoMessage("Info", "Godot version installed successfully!")));
        }
Esempio n. 13
0
        /// <summary>
        /// Main process
        /// </summary>
        private static void Process(string[] args)
        {
            Console.WriteLine("FOLDER ZIP AND UPLOAD v2.0");
            Console.WriteLine("by Daniele Arrighi @ Idioblast. [email protected]");
            Console.WriteLine();
            Console.WriteLine("Processing...");

            //LOG
            Utilities.WriteToFile(string.Format("{0}: Executing...", DateTime.Now));

            /********************
            * DEFAULTS VALUES
            ********************/
            //ZIPs Temporary Path
            string zipDestinationFolder = ConfigurationManager.AppSettings["ZipDestinationFolder"];

            if (!zipDestinationFolder.EndsWith("\\"))
            {
                zipDestinationFolder += "\\";
            }

            //Configuration File to Load
            string configurationFile = AppDomain.CurrentDomain.BaseDirectory + "config.xml";

            //Verbosity
            bool verbose = false;

            /********************
            * OVERWRITE DEFAULT VALUES WITH COMMAND ARGUMENTS IF PRESENT
            ********************/
            var options = new Options();

            if (Parser.Default.ParseArguments(args, options))
            {
                //Verbosity
                verbose = options.Verbose;

                //ZIPs Temporary Path
                if (!string.IsNullOrEmpty(options.ZipDestinationFolder))
                {
                    zipDestinationFolder = options.ZipDestinationFolder;
                }

                //Configuration File to Load
                if (!string.IsNullOrEmpty(options.ConfigFile))
                {
                    configurationFile = options.ConfigFile;
                }

                //Outputs the encrypted password to save in configuration file.
                if (!string.IsNullOrEmpty(options.Password))
                {
                    Console.WriteLine("Encrypted Password is: {0}", Security.EncryptText(options.Password));
                    Console.WriteLine("Press any key to exit...");
                    Console.ReadKey();
                    return;
                }
            }

            /********************
            * CONFIGURATION
            ********************/

            //Checks if configuration files exist
            if (!File.Exists(configurationFile))
            {
                Utilities.WriteToFile(string.Format("Missing Configuration File At {0}", configurationFile));

                Console.WriteLine("Missing Configuration File At {0}", configurationFile);
                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
                return;
            }

            //Checks if the Temporary Directory Exist, or create it
            if (!Directory.Exists(zipDestinationFolder))
            {
                Directory.CreateDirectory(zipDestinationFolder);
            }

            //Gets the folders to process from XML file
            ProcessQueue folderQueue = new ProcessQueue(configurationFile);

            //Setup Directory Names
            string nowFileName = DateTime.Now.ToString("yyyyMMdd");

            /********************
            * PROCESS THE QUEUE
            ********************/
            foreach (QueueItem queue in folderQueue.Queue)
            {
                //Extra checks
                if (!queue.FtpDirectory.EndsWith("/"))
                {
                    queue.FtpDirectory += "/";
                }
                if (!queue.Directory.EndsWith("\\"))
                {
                    queue.Directory += "\\";
                }

                //Password check
                if (String.IsNullOrEmpty(queue.FtpPassword))
                {
                    Utilities.WriteToFile("Error. Missing password (Encrypted) for FTP connection");
                    Console.WriteLine("Error. Missing password (Encrypted) for FTP connection");
                    continue;
                }
                else
                {
                    try
                    {
                        queue.FtpPassword = Security.DecryptText(queue.FtpPassword);
                    }
                    catch
                    {
                        Utilities.WriteToFile("Error. Wrong password format");
                        Console.WriteLine("Error. Wrong password format");
                        continue;
                    }
                }

                //ELABORATES ALL THE FOLDERS TO ZIP AND UPLOAD
                if (queue.ProcessSubDirectories)
                {
                    DirectoryInfo startingDirectory = new DirectoryInfo(queue.Directory);
                    foreach (var currentDirectory in startingDirectory.GetDirectories())
                    {
                        if (!queue.IsPathExcluded(currentDirectory.FullName))
                        {
                            WorkPath w = new WorkPath();

                            w.FullPath    = currentDirectory.FullName;
                            w.FullZipPath = Path.Combine(zipDestinationFolder, currentDirectory.Name + ".zip");

                            if (queue.AppendDateTime)
                            {
                                w.FullZipPath = Path.Combine(zipDestinationFolder,
                                                             String.Format("{0:yyyMMddHHmmss}-{1}.zip", DateTime.Now, currentDirectory.Name));
                            }

                            w.IsZipped = ZipService.ZipFolder(currentDirectory.FullName, w.FullZipPath,
                                                              queue.ExcludedFolders.ToStringArray(), verbose);
                            w.IsUploaded = false;

                            queue.WorkList.Add(w);
                        }
                    }
                }
                else
                {
                    //IF SHOULD NOT PROCSS SUBDIRS, ZIP THE DIRECTORY DIRECTLY
                    DirectoryInfo currentDirectory = new DirectoryInfo(queue.Directory);
                    if (!queue.IsPathExcluded(currentDirectory.FullName))
                    {
                        WorkPath w = new WorkPath();

                        w.FullPath    = currentDirectory.FullName;
                        w.FullZipPath = Path.Combine(zipDestinationFolder, currentDirectory.Name + ".zip");

                        if (queue.AppendDateTime)
                        {
                            w.FullZipPath = Path.Combine(zipDestinationFolder,
                                                         String.Format("{0:yyyMMddHHmmss}-{1}.zip", DateTime.Now, currentDirectory.Name));
                        }

                        w.IsZipped = ZipService.ZipFolder(currentDirectory.FullName, w.FullZipPath,
                                                          queue.ExcludedFolders.ToStringArray(), verbose);
                        w.IsUploaded = false;

                        queue.WorkList.Add(w);
                    }
                }

                //FTP UPLOAD ALL ELABORATED FOLDER
                bool uploadSuccess = FtpService.UploadQueue(queue, queue.FtpDirectory + nowFileName + "/", queue.FtpServer, queue.FtpUser, queue.FtpPassword, verbose);

                //DELETE OLDER FOLDERS IF REQUIRED
                //TODO: Use same session in UploadQueue and in CleanOldRemoteFolders
                if (queue.CleanRemote > 0 && uploadSuccess)
                {
                    FtpService.CleanOldRemoteFolders(queue.CleanRemote, verbose, queue.FtpDirectory, queue.FtpServer, queue.FtpUser, queue.FtpPassword);
                }

                //DELETE ALL CREATED ZIP FILES
                if (queue.DeleteFilesWhenFinished)
                {
                    FileService.DeleteFilesInQueue(queue, verbose);
                }
            }

            //LOG
            Utilities.WriteToFile(String.Format("Zip & Upload routine completed at: {0}\n", DateTime.Now));

            //SEND MAIL
            string subject = String.Format("Zip & Upload routine completed at: {0}", DateTime.Now); //Todo: Send more information in the mail body.

            MailService.Send("Zip & Upload Executed", subject, verbose);

            //DONE
            if (verbose)
            {
                Console.WriteLine();
                Console.WriteLine("Press any key to exit...");
                Console.ReadLine();
            }
        }
Esempio n. 14
0
        private readonly string baseUrl = "https://appbuilderapifunctions.azurewebsites.net/api"; /*@"http://localhost:7071/api";*/

        public StorageClient(HttpClient client, ZipService zipService)
        {
            _client     = client;
            _zipService = zipService;
        }
        public void OpenTest()
        {
            var zipService = new ZipService(new AzureStorageRepository());

            zipService.OpenZip();
        }