Example #1
0
    private static void CollectLogFiles(string dataPath, string outputPath, List<string> products)
    {
      if (!Directory.Exists(outputPath))
        Directory.CreateDirectory(outputPath);

      string targetFile = string.Format("MediaPortal2-Logs-{0}.zip", DateTime.Now.ToString("yyyy-MM-dd-HH.mm.ss"));
      targetFile = Path.Combine(outputPath, targetFile);
      if (File.Exists(targetFile))
        File.Delete(targetFile);

      ZipFile archive = new ZipFile(targetFile);
      foreach (var product in products)
      {
        string sourceFolder = Path.Combine(dataPath, @"Team MediaPortal", product, "Log");
        if (!Directory.Exists(sourceFolder))
        {
          Console.WriteLine("Skipping non-existant folder {0}", sourceFolder);
          continue;
        }
        Console.WriteLine("Adding folder {0}", sourceFolder);
        try
        {
          archive.AddDirectory(sourceFolder, product);
        }
        catch (Exception ex)
        {
          Console.WriteLine("Error adding folder {0}: {1}", sourceFolder, ex);
        }
      }
      archive.Save();
      archive.Dispose();
      Console.WriteLine("Successful created log archive: {0}", targetFile);

      Process.Start(outputPath); // Opens output folder
    }
Example #2
0
        void webClient_DownloadFileCompletedPatch(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"TheLongDrive\Mods");

            downloadbar.Value = 80;
            downloadperc.Text = "Unzipping...";

            sw.Stop();
            //     MessageBox.Show(this, "Download complete!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

            Ionic.Zip.ZipFile zipFile = new Ionic.Zip.ZipFile(path + "/" + "temp/TLDPatcherNEW.zip");
            zipFile.ZipError        += new EventHandler <Ionic.Zip.ZipErrorEventArgs>(zip_Error);
            zipFile.ExtractProgress += new EventHandler <ExtractProgressEventArgs>(zip_Progress);
            try
            {
                zipFile.ExtractAll(path + "/temp/", ExtractExistingFileAction.OverwriteSilently);
                download.Enabled    = true;
                mymods.Enabled      = true;
                downpatcher.Enabled = true;
                downloadperc.Text   = "Complete!";
                downloadbar.Value   = 100;
                zipFile.Dispose();
                webClient.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Close TLDPatcher!");
            }
            System.IO.File.Copy(path + "/temp/patcher/TLDLoader.dll", Application.StartupPath + "/TLDLoader.dll", true);
            Process.Start(path + "/temp/patcher/TLDPatcher.exe", "\"" + path + "/temp/patcher/" + "\"");
        }
Example #3
0
            static void Main(string[] args) {
               
               string ZipFilePath = Path.Combine("", "TestArchive.zip");
               if (File.Exists(ZipFilePath)) File.Delete(ZipFilePath);
                var zip = new ZipFile(ZipFilePath);
                zip.AddDirectory("LocalVFS", "LocalVFS/");
                zip.Save();
                zip.Dispose();
                //
                ZipFileSystemConfiguration zc = ZipFileSystemConfiguration.CreateDefaultConfig(ZipFilePath,"_tmp_");
                ZipFileProvider lp = new ZipFileProvider(zc);
                bool exfd = lp.ExistFolder("LocalVFS/", true);
                if (exfd) {
                    lp.DeleteFolder("LocalVFS/");
                }
                byte[] dataTest = Encoding.UTF8.GetBytes("this is a test context!!!");
                File.WriteAllBytes("test.cs", dataTest);
                lp.CreateFolder("LocalVFS/");
                string filepath = lp.CreateFilePath("LocalVFS/", "test.txt");

                //lp.MoveFile("test.cs", filepath);
                byte[] dataTest2 = Encoding.UTF8.GetBytes("this is a test write data!!!");
                using (MemoryStream ms = new MemoryStream(dataTest2)) {
                    lp.WriteFile("LocalVFS/test.txt", ms, true, dataTest2.Length, ContentUtil.UnknownContentType);
                }
                //lp.DeleteFile("LocalVFS/test.txt");
                lp.CopyFolder("LocalVFS/", "localvfs_test/");
                lp.Dispose();
                int jj = 0;
            }
    /// <summary>
    /// Returns a file system implementation, which is assigned
    /// to the <see cref="TestContext.FileSystem"/> property.
    /// </summary>
    /// <param name="localTestFolder">The temporary test folder that is
    /// used by the context. This is actually just the <see cref="TestContext.LocalTestRoot"/>
    /// reference.</param>
    protected override IFileSystemProvider InitFileSystem(DirectoryInfo localTestFolder)
    {
      //init empty zip file
      ZipFilePath = Path.Combine(localTestFolder.FullName, "TestArchive.zip");
      var zip = new ZipFile(ZipFilePath);
      zip.Save();
      zip.Dispose();

      //init transfer stores
      var downloadTransferStore = new TestTransferStore<ZipDownloadTransfer>();
      var uploadTransferStore = new TestTransferStore<ZipUploadTransfer>();

      //init configuration
      var tempFactory = new TempFileStreamFactory(LocalTestRoot.FullName);

      var zipFile = new FileInfo(ZipFilePath);

      var configuration = new ZipFileSystemConfiguration(zipFile, tempFactory);
      configuration.RootName = "Test Root";
      configuration.DownloadStore = downloadTransferStore;
      configuration.UploadStore = uploadTransferStore;
      configuration.DownloadTokenExpirationTime = TimeSpan.FromHours(24);
      configuration.UploadTokenExpirationTime = TimeSpan.FromHours(24);
      configuration.DefaultDownloadBlockSize = 32768;
      configuration.MaxDownloadBlockSize = 32768 * 2;
      configuration.MaxUploadBlockSize = 32768 * 4;
      configuration.MaxUploadFileSize = (long)1024 * 1024 * 2048; //2GB limit



      //create provider
      Provider = new ZipFileProvider(configuration);
      return Provider;
    }
Example #5
0
        private void bgWorker_Finish(object sender, RunWorkerCompletedEventArgs e)
        {
            dlElapsedTimer.Stop();
            try
            {
                if (File.Exists(zipTarget))
                {
                    using (ZipFile zip = new ZipFile(zipTarget))
                    {
                        zip.ExtractAll(Directory.GetCurrentDirectory(), ExtractExistingFileAction.OverwriteSilently);
                        zip.Dispose();
                    }

                    File.Delete(zipTarget);
                    Process start = new Process();
                    start.StartInfo.FileName = exeTarget;
                    start.StartInfo.Arguments = "ProcessStart.cs";
                    start.Start();
                    Application.Exit();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was an error with the updater. Check your connection and try running as an administrator.\r\n\r\n" + ex.Message);
                Application.Exit();
            }
        }
Example #6
0
		public OperationResult<bool> GKWriteConfiguration(Guid clientUID, Guid deviceUID)
		{
			var device = GKManager.Devices.FirstOrDefault(x => x.UID == deviceUID);
			if (device != null)
			{
				var progressCallback = new GKProgressCallback();
				ServerTaskRunner.Add(progressCallback, "Запись конфигурации ГК", (() =>
				{
					if (GKManager.DeviceConfiguration.OnlyGKDeviceConfiguration)
					{
						var deviceConfigFileName = AppDataFolderHelper.GetServerAppDataPath("Config" + Path.DirectorySeparatorChar + "GKDeviceConfiguration.xml");
						var zipDeviceConfigFileName = AppDataFolderHelper.GetServerAppDataPath("GKDeviceConfiguration.fscp");
						if (File.Exists(zipDeviceConfigFileName))
							File.Delete(zipDeviceConfigFileName);
						var zipFile = new ZipFile(zipDeviceConfigFileName);
						zipFile.AddFile(deviceConfigFileName, "");
						zipFile.Save(zipDeviceConfigFileName);
						zipFile.Dispose();
					}
					var result = GKProcessorManager.GKWriteConfiguration(device, GetUserName(clientUID), progressCallback, clientUID);
					NotifyOperationResult_WriteConfiguration(result, clientUID);
				}
				));
				return new OperationResult<bool>(true);
			}
			return OperationResult<bool>.FromError("Не найдено устройство в конфигурации. Предварительно необходимо применить конфигурацию");
		}
Example #7
0
 public void GivenIUnzipThatPackageIntoADeploymentFolder()
 {
     var folder = (string)ScenarioContext.Current["targetFolder"];
     if (Directory.Exists(folder)) 
         Directory.Delete(folder, true);
     var zip = new ZipFile((string)ScenarioContext.Current["targetZip"]);
     zip.ExtractAll(folder);
     zip.Dispose();
 }
Example #8
0
 public string zipFolder(string strPathOfFolderToZip, string strTargetZipFileName)
 {
     var zpZipFile = new ZipFile(strTargetZipFileName);
     zpZipFile.AddDirectory(strPathOfFolderToZip, "");
     //zpZipFile.TrimVolumeFromFullyQualifiedPaths = true;
     zpZipFile.Save();
     zpZipFile.Dispose();
     return strTargetZipFileName;
 }
 private void DownloadSupportFile(string fileName)
 {
     string fileSourceUrl = "http://DeltaEngine.net/" + AndroidDriverFolderName + "/" + fileName;
     string targetFilePath = Path.Combine(AndroidDriverFolderName, fileName);
     new WebClient().DownloadFile(fileSourceUrl, targetFilePath);
     var driversFile = new ZipFile(targetFilePath);
     driversFile.ExtractAll(DownloadDirectory, ExtractExistingFileAction.OverwriteSilently);
     driversFile.Dispose();
     File.Delete(targetFilePath);
 }
Example #10
0
 public static void UnzipIPSW()
 {
     //Removing Previous...
     Folder_Delete(temppath + "\\IPSW");
     //Unzip IPSW...
     using (Ionic.Zip.ZipFile zip1 = Ionic.Zip.ZipFile.Read(ipsw)) {
         Application.DoEvents();
         zip1.ExtractAll(temppath + "\\IPSW", true);
         zip1.Dispose();
     }
 }
Example #11
0
 public bool CreatEmptyZipFile(string zipfilepath) {
     try {
         if (File.Exists(zipfilepath)) File.Delete(zipfilepath);
         ZipFile zip = new ZipFile(zipfilepath);
         zip.Save();
         zip.Dispose();
         return true;
     }
     catch { 
         
     }
     return false;
 }
Example #12
0
 private void InstallVCPP_DoWork(System.Object sender, System.ComponentModel.DoWorkEventArgs e)
 {
     //Visual C++ 2008 Redistributable Installer
     //Copyright (C) 2007 Microsoft
     SaveToDisk("vcpp.zip", temppath + "\\vcpp.zip");
     using (Ionic.Zip.ZipFile zip1 = Ionic.Zip.ZipFile.Read(temppath + "\\vcpp.zip")) {
         zip1.ExtractAll(temppath + "\\");
         zip1.Dispose();
     }
     Delay(1);
     //write to buffer
     cmdline = Quotation + temppath + "\\install.exe" + Quotation + " /q";
     ExecCmd(cmdline, true);
 }
Example #13
0
    public void ExtractResources()
    {
        SaveToDisk("Resources.zip", temppath + "\\Resources.zip");
        SaveToDisk("iFaith." + xml_ipsw_md5 + ".zip", temppath + "\\iFaith.bundle.zip");

        //Primary Resources...
        using (Ionic.Zip.ZipFile zip1 = Ionic.Zip.ZipFile.Read(temppath + "\\Resources.zip")) {
            zip1.ExtractAll(temppath + "\\", true);
            zip1.Dispose();
        }
        //iFaith bundle...
        using (Ionic.Zip.ZipFile zip1 = Ionic.Zip.ZipFile.Read(temppath + "\\iFaith.bundle.zip")) {
            zip1.ExtractAll(temppath + "\\", true);
            zip1.Dispose();
        }
    }
Example #14
0
        /// <summary>
        /// Streams a local zip file using a streamreader.
        /// Important: the caller must call Dispose() on the returned ZipFile instance.
        /// </summary>
        /// <param name="filename">Location of the original zip file</param>
        /// <param name="zipEntryName">The zip entry name to open a reader for. Specify null to access the first entry</param>
        /// <param name="zip">The ZipFile instance to be returned to the caller</param>
        /// <returns>Stream reader of the first file contents in the zip file</returns>
        public static StreamReader Unzip(string filename, string zipEntryName, out ZipFile zip)
        {
            StreamReader reader = null;

            zip = null;

            try
            {
                if (File.Exists(filename))
                {
                    try
                    {
                        zip = new ZipFile(filename);
                        var entry = zip.FirstOrDefault(x => zipEntryName == null || string.Compare(x.FileName, zipEntryName, StringComparison.OrdinalIgnoreCase) == 0);
                        if (entry == null)
                        {
                            // Unable to locate zip entry
                            return(null);
                        }

                        reader = new StreamReader(entry.OpenReader());
                    }
                    catch (Exception err)
                    {
                        Log.Error(err, "Inner try/catch");
                        if (zip != null)
                        {
                            zip.Dispose();
                        }
                        if (reader != null)
                        {
                            reader.Close();
                        }
                    }
                }
                else
                {
                    Log.Error($"Data.UnZip(2): File doesn\'t exist: {filename}");
                }
            }
            catch (Exception err)
            {
                Log.Error(err, "File: " + filename);
            }
            return(reader);
        }
Example #15
0
 /// <summary>
 /// Función que se utiliza para comprimir una carpeta o un archivo
 /// </summary>
 /// <param name="path"> Ruta fisica del archivo o carpeta a comprimir </param>
 /// <param name="fileOrForlder"> Indica si lo que se desea comprimir es un Archivo o una carpeta </param>
 /// <returns> True si la operación se completo sin problemas </returns>
 /// <remarks>
 /// <list> Creado Agosto 14 de 2013 - Ing david pineda </list>
 /// </remarks>
 public static void generarZip(string path, bool fileOrForlder)
 {
     ZipFile zip = new ZipFile();
     try
     {
         if (fileOrForlder)
         {
             //Si es un Archivo
             using (zip)
             {
                 zip.AddFile(path);
                 string path_zip = path.Replace(Path.GetFileName(path), Path.Combine(Path.GetFileNameWithoutExtension(path), ".zip"));
                 if (System.IO.File.Exists(path_zip))
                 {
                     System.IO.File.Delete(path_zip);
                 }
                 zip.Save(path_zip);
             }
         }
         else
         {
             //Si es un Folder - Carpeta
             using (zip)
             {
                 zip.AddDirectory(path);
                 string path_zip = path + ".zip";
                 if (System.IO.File.Exists(path_zip))
                 {
                     System.IO.File.Delete(path_zip);
                 }
                 zip.Save(path_zip);
             }
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
     finally
     {
         //Se agrega la el Dispose para asegurar que se liberen recursos
         zip.Dispose();
     }
 }
		public static void SaveToZipFile(string fileName, XDeviceConfiguration deviceConfiguration)
		{
			var folderName = AppDataFolderHelper.GetTempFolder();
			if (!Directory.Exists(folderName))
				Directory.CreateDirectory(folderName);

			if (File.Exists(fileName))
				File.Delete(fileName);

			deviceConfiguration.BeforeSave();
			deviceConfiguration.Version = new ConfigurationVersion() { MinorVersion = 1, MajorVersion = 1 };
			ZipSerializeHelper.Serialize(deviceConfiguration, Path.Combine(folderName, "XDeviceConfiguration.xml"));
			var zipFile = new ZipFile(fileName);
			zipFile.AddDirectory(folderName);
			zipFile.Save(fileName);
			zipFile.Dispose();
			if (Directory.Exists(folderName))
				Directory.Delete(folderName, true);
		}
Example #17
0
        void ExtractZIPAsync()
        {
            // Extract outer archive

            System.IO.Compression.ZipFile.ExtractToDirectory(
                Path.Combine(HoI4Path, $"{ID}.zip"),
                Path.Combine(HoI4Path, $"_{ID}_tmp"));

            var innerArchiveName = Directory.GetFiles(Path.Combine(HoI4Path, $"_{ID}_tmp", $"{ID}"))[0];

            // Extract inner archive

            ZipFile zip = ZipFile.Read(innerArchiveName);

            zip.ExtractProgress += ZIPProgressBarUpdater;
            Directory.CreateDirectory(Path.Combine(HoI4Path, $"{ID}"));
            zip.ExtractAll(Path.Combine(HoI4Path, $"{ID}"), ExtractExistingFileAction.OverwriteSilently);
            zip.Dispose();
        }
Example #18
0
        public static string ZipConvertedAudioFiles(IEnumerable<string> convertedAudioFilenames)
        {
            var zippedFileName = string.Empty;

            try
            {
                zippedFileName = FileNameGenerationHelper.GenerateFilename();
                var zip = new ZipFile(Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"), zippedFileName));
                zip.AddFiles(convertedAudioFilenames.Select(caf => Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"), caf)), false, "");
                zip.Save();
                zip.Dispose();
            }
            catch (Exception e)
            {
                throw new ZipException(e.Message);
            }

            return zippedFileName;
        }
Example #19
0
        private void LoadZipFile(ZipFile ZipFileObject)
        {
            try
            {
                Response.ClearContent();
                Response.AppendHeader("Content-Disposition", "attachment; filename=Comprobantes.zip");
                Response.ContentType = "application/x-zip-compressed";

                ZipFileObject.Save(Response.OutputStream);

                Response.End();

                ZipFileObject.Dispose();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
                Response.End();
            }
        }
Example #20
0
		public static string zip_Files(this List<string> filesToZip, string targetZipFile)//, string baseFolder)
		{		
			"Creating ZipFile with {0} files to {1}".info(filesToZip.size(), targetZipFile);
			if (targetZipFile.fileExists())
				Files.deleteFile(targetZipFile);
            var zpZipFile = new ZipFile(targetZipFile);            
            foreach(var fileToZip in filesToZip)
            {            	
            	{
            		zpZipFile.AddFile(fileToZip);            
            	}
            	//catch(Exception ex)
            	{
            	//	"[zip_Files] {0} in file {1}".error(ex.Message, fileToZip);
            	}
            }
            zpZipFile.Save();
            zpZipFile.Dispose();
            return targetZipFile;        
		}
Example #21
0
        private async Task RunAsync(CancellationToken cancellationToken)
        {
            // TODO: Replace the following with your own logic.
            while (!cancellationToken.IsCancellationRequested)
            {
                /*
                 * To backup all files to folder backups every 60s. And save no more than 5 backup files. 
                 * If you want to change the blob container, you can change the "blobcontainer" to your blob container name.
                 */
                var blobStorage = new BlobStorage("blobcontainer");
                //Use local storage
                LocalResource myStorage = RoleEnvironment.GetLocalResource("Backup");
                string filePath = Path.Combine(myStorage.RootPath, "backup");
                Directory.CreateDirectory(filePath);

                //Download all files to local storage
                blobStorage.DownloadToLocalStorage(myStorage, "", filePath);
                //Zip the directory
                ZipFile zipFile = new ZipFile();
                string zipPath = filePath + ".zip";
                zipFile.AddDirectory(filePath);
                zipFile.Save(zipPath);
                zipFile.Dispose();
                //Put it back to archives folder of container
                string uploadPath = Path.Combine("backups", Path.GetFileNameWithoutExtension(zipPath) + "-" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".zip");
                blobStorage.PutBlob(uploadPath, zipPath);

                var blobs = blobStorage.Container.ListBlobs("backups/", false, BlobListingDetails.None);

                //No more than 5 backup files
                if(blobs.Count() > 5)
                {
                    var deleteBlob = blobs.OrderBy(b => b.Uri.ToString()).First();
                    var blob = blobStorage.Container.GetBlockBlobReference("backups/" + Path.GetFileName(deleteBlob.Uri.ToString()));
                    blob.Delete();
                }

                Trace.TraceInformation("Working");
                await Task.Delay(60000);
            }
        }
Example #22
0
 /// <summary>
 /// Loads the specified zipfile.
 /// 
 /// </summary>
 /// <param name="zipfile">The zipfile.</param>
 /// <returns>if something wrong, return null else the loaded package</returns>
 public PackageClass Load(string zipfile)
 {
   try
   {
     PackageClass pak = new PackageClass();
     _zipPackageFile = ZipFile.Read(zipfile);
     string tempPackageFile = Path.GetTempFileName();
     var fs = new FileStream(tempPackageFile, FileMode.Create);
     _zipPackageFile["MediaPortalExtension.xml"].Extract(fs);
     fs.Close();
     pak.Load(tempPackageFile);
     _tempFileList.Add(tempPackageFile);
     foreach (FileItem fileItem in pak.UniqueFileList.Items)
     {
       if (fileItem.SystemFile)
       {
         string tempfil = Path.GetTempFileName();
         tempfil = Path.Combine(Path.GetDirectoryName(tempfil), Path.GetFileNameWithoutExtension(tempfil) +
                   Path.GetExtension(fileItem.LocalFileName));
         Extract(fileItem, tempfil);
         fileItem.TempFileLocation = tempfil;
         //fileItem.LocalFileName = tempfil;
         _tempFileList.Add(tempfil);
       }
     }
     pak.ZipProvider = this;
     pak.GetFilePaths();
     pak.GeneralInfo.Location = zipfile;
     return pak;
   }
   catch (Exception)
   {
     if (_zipPackageFile != null)
       _zipPackageFile.Dispose();
     return null;
   }
 }
Example #23
0
        public void DoUpdateNKH()
        {
            new Thread(() =>
            {
                WebHandler web = new WebHandler();
                string nkhfolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\NKHook5";
                string savePath = nkhfolder + "\\NKHook5.zip";

                if(!web.CheckForUpdate(versionsURL, "NKHook5: ", 3, Serializer.cfg.NKHookVersion) && Directory.Exists(nkhfolder)
                && File.Exists(nkhfolder + "\\NKHook5.dll") && File.Exists(nkhfolder + "\\NKHook5-CLR.dll"))
                    return;

                if (File.Exists(savePath))
                    File.Delete(savePath);

                if (!Directory.Exists(nkhfolder))
                    Directory.CreateDirectory(nkhfolder);

                web.DownloadFile("NKHook5", versionsURL, savePath, "NKHook5: ", 3);


                string extractPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\NKHook5";
                ZipFile archive = new ZipFile(savePath);
                archive.ExtractAll(extractPath, ExtractExistingFileAction.OverwriteSilently);
                archive.Dispose();

                if (File.Exists(savePath))
                    File.Delete(savePath);

                if (File.Exists(Environment.CurrentDirectory + "\\NKHook5-Injector.exe"))
                    File.Delete(Environment.CurrentDirectory + "\\NKHook5-Injector.exe");

                //File.Copy(nkhEXE, Environment.CurrentDirectory + "\\NKHook5-Injector.exe");
                Serializer.cfg.NKHookVersion = web.LatestVersionNumber;
                Serializer.SaveSettings();
            }).Start();
        }
Example #24
0
 private void button14_Click(object sender, EventArgs e)
 {
     try
     {
         string link = @"https://www.dropbox.com/s/b7rh3z9ake3zefp/windows_64bit.zip?dl=1";
         string path = Environment.CurrentDirectory;
         Directory.CreateDirectory(path + @"\Discord-RPC-Extension");
         WebClient webClient = new WebClient();
         webClient.DownloadFileCompleted += ((object se, AsyncCompletedEventArgs ev) => {
             using (Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(path + @"\Discord-RPC-Extension\Extension.zip"))
             {
                 foreach (ZipEntry evu in zip)
                 {
                     evu.Extract(path + @"\Discord-RPC-Extension", ExtractExistingFileAction.OverwriteSilently);
                 }
                 zip.Dispose();
             }
             File.Delete(path + @"\Discord-RPC-Extension\Extension.zip");
             MessageBox.Show("Установка успешно завершена!", "CustomStatus");
             if (Properties.YGRPC.Default.ClientStartMode == 0)
             {
                 Process.Start(path + @"\Discord-RPC-Extension\add_startup.bat");
             }
             if (Properties.YGRPC.Default.ClientStartMode != 2)
             {
                 ProcessStartInfo procInfo = new ProcessStartInfo();
                 procInfo.FileName = path + @"\Discord-RPC-Extension\server_win.exe";
                 winServer = new Process {
                     StartInfo = procInfo
                 };
                 winServer.Start();
             }
         });
         webClient.DownloadFileAsync(new Uri(link), path + @"\Discord-RPC-Extension\Extension.zip");
     }
     catch (Exception ex) { MessageBox.Show("Ошибка во время установки: " + ex.Message, "CustomStatus"); }
 }
Example #25
0
        private static ZipOutputStream CreateNewStream(ArrayList htmlFile, string outPath, out long HTMLstreamlenght)
        {
            ZipOutputStream oZipStream = new ZipOutputStream(File.Create(outPath), false);// create zip stream

            // Compression level of zip file.

            oZipStream.CompressionLevel = 0;
            const int BufferSize = 4096;

            byte[] obuffer = new byte[BufferSize];
            HTMLstreamlenght = 0;
            //FileStream htmlstream = null;
            ZipEntry oHtmlEntry = new ZipEntry();

            using (Ionic.Zip.ZipFile htmlZip = new Ionic.Zip.ZipFile())
            {
                foreach (string htmlFil in htmlFile.ToArray()) // for each file, generate a zip entry
                {
                    oHtmlEntry = htmlZip.AddEntry(Path.GetFileName(htmlFil.ToString()), htmlFil);
                    oZipStream.PutNextEntry(oHtmlEntry.FileName);
                    using (FileStream htmlstream = File.OpenRead(htmlFil))
                    {
                        int read;
                        while ((read = htmlstream.Read(obuffer, 0, obuffer.Length)) > 0)
                        {
                            oZipStream.Write(obuffer, 0, read);
                        }
                    }
                }
                htmlZip.Dispose();
            }
            HTMLstreamlenght = oZipStream.Position;


            return(oZipStream);
        }
Example #26
0
        /// <summary>
        ///   Checks a zip file to see if its directory is consistent,
        ///   and optionally fixes the directory if necessary.
        /// </summary>
        ///
        /// <remarks>
        ///
        /// <para>
        ///   In cases of data error, the directory within a zip file can get out of
        ///   synch with the entries in the zip file.  This method checks the given
        ///   zip file, and returns true if this has occurred. It also optionally
        ///   fixes the zipfile, saving the fixed copy in <em>Name</em>_Fixed.zip.
        /// </para>
        ///
        /// <para>
        ///   This method may take a long time to run for large zip files.  It
        ///   will take even longer if the file actually needs to be fixed, and if
        ///   <c>fixIfNecessary</c> is true.
        /// </para>
        ///
        /// <para>
        ///   This method is not supported in the Reduced or Compact
        ///   Framework versions of DotNetZip.
        /// </para>
        ///
        /// </remarks>
        ///
        /// <param name="zipFileName">The filename to of the zip file to check.</param>
        ///
        /// <param name="fixIfNecessary">If true, the method will fix the zip file if
        ///     necessary.</param>
        ///
        /// <param name="writer">
        /// a TextWriter in which messages generated while checking will be written.
        /// </param>
        ///
        /// <returns>true if the named zip is OK; false if the file needs to be fixed.</returns>
        ///
        /// <seealso cref="CheckZip(string)"/>
        /// <seealso cref="FixZipDirectory(string)"/>
        public static bool CheckZip(Stream zipFileStream, Stream fixedZipFileStream,
                                    TextWriter writer)

        {
            ZipFile zip1 = null, zip2 = null;
            bool    isOk = true;

            try
            {
                var stream = new OffsetStream(zipFileStream);
                zip1 = ZipFile.Read(stream, new ReadOptions {
                    FullScan = true
                });

                stream.Seek(0, SeekOrigin.Begin);
                zip2 = ZipFile.Read(stream);

                foreach (var e1 in zip1)
                {
                    foreach (var e2 in zip2)
                    {
                        if (e1.FileName == e2.FileName)
                        {
                            if (e1._RelativeOffsetOfLocalHeader != e2._RelativeOffsetOfLocalHeader)
                            {
                                isOk = false;
                                if (writer != null)
                                {
                                    writer.WriteLine("{0}: mismatch in RelativeOffsetOfLocalHeader  (0x{1:X16} != 0x{2:X16})",
                                                     e1.FileName, e1._RelativeOffsetOfLocalHeader,
                                                     e2._RelativeOffsetOfLocalHeader);
                                }
                            }
                            if (e1._CompressedSize != e2._CompressedSize)
                            {
                                isOk = false;
                                if (writer != null)
                                {
                                    writer.WriteLine("{0}: mismatch in CompressedSize  (0x{1:X16} != 0x{2:X16})",
                                                     e1.FileName, e1._CompressedSize,
                                                     e2._CompressedSize);
                                }
                            }
                            if (e1._UncompressedSize != e2._UncompressedSize)
                            {
                                isOk = false;
                                if (writer != null)
                                {
                                    writer.WriteLine("{0}: mismatch in UncompressedSize  (0x{1:X16} != 0x{2:X16})",
                                                     e1.FileName, e1._UncompressedSize,
                                                     e2._UncompressedSize);
                                }
                            }
                            if (e1.CompressionMethod != e2.CompressionMethod)
                            {
                                isOk = false;
                                if (writer != null)
                                {
                                    writer.WriteLine("{0}: mismatch in CompressionMethod  (0x{1:X4} != 0x{2:X4})",
                                                     e1.FileName, e1.CompressionMethod,
                                                     e2.CompressionMethod);
                                }
                            }
                            if (e1.Crc != e2.Crc)
                            {
                                isOk = false;
                                if (writer != null)
                                {
                                    writer.WriteLine("{0}: mismatch in Crc32  (0x{1:X4} != 0x{2:X4})",
                                                     e1.FileName, e1.Crc,
                                                     e2.Crc);
                                }
                            }

                            // found a match, so stop the inside loop
                            break;
                        }
                    }
                }

                zip2.Dispose();
                zip2 = null;

                if (!isOk && fixedZipFileStream != null)
                {
                    zip1.Save(fixedZipFileStream);
                }
            }
            finally
            {
                if (zip1 != null)
                {
                    zip1.Dispose();
                }
                if (zip2 != null)
                {
                    zip2.Dispose();
                }
            }
            return(isOk);
        }
Example #27
0
        // Installing and uninstalling of addon, could be neater >,>
        // Refactor plz
        public void InstallAddon(AddonMetaData addon)
        {
            // Check we have a path for the Firefall install
            if (!Statics.IsFirefallInstallValid(MeldiiSettings.Self.FirefallInstallPath))
            {
                MainWindow.ShowAlert("Error: Invalid path to Firefall install!",
                    string.Format("\"{0}\" is not a valid Firefall install\nPlease go to settings and set the path to your Firefall install",
                    MeldiiSettings.Self.FirefallInstallPath));

                return;
            }

            MainView.StatusMessage = string.Format("Installing Addon {0}", addon.Name);

            addon.InstalledFilesList.Clear();

            string dest = addon.IsAddon ? Statics.AddonsFolder : Statics.GetPathForMod(addon.Destination);
            string installInfoDest = addon.IsAddon ? Path.Combine(Statics.AddonsFolder, "melder_addons") : Path.Combine(MeldiiSettings.Self.FirefallInstallPath, Statics.ModDataStoreReltivePath);
            installInfoDest = Path.Combine(installInfoDest, Path.GetFileName(addon.ZipName) + ".ini");

            // Prep for back up
            ZipFile BackupZip = null;
            if (!addon.IsAddon)
            {
                BackupZip = new ZipFile();

                // Back up files
                foreach (string file in addon.RemoveFilesList)
                {
                    string modFilePath = Path.Combine(dest, file.ToLower().Replace(addon.Destination.ToLower(), ""));
                    if (File.Exists(modFilePath) && Statics.IsPathSafe(modFilePath))
                    {
                        Debug.WriteLine("Install, backing up file: " + modFilePath);
                        string basePath = Path.GetDirectoryName(modFilePath.Replace(Statics.GetFirefallSystemDir(), ""));
                        BackupZip.AddFile(modFilePath, basePath);
                    }
                }

                using (ZipFile zip = ZipFile.Read(addon.ZipName))
                {
                    foreach (string file in zip.EntryFileNames)
                    {
                        string modFilePath = Path.Combine(dest, file);
                        if (File.Exists(modFilePath) && Statics.IsPathSafe(modFilePath))
                        {
                            Debug.WriteLine("Install, backing up file: " + modFilePath);
                            string basePath = Path.GetDirectoryName(modFilePath.Replace(Statics.GetFirefallSystemDir(), ""));
                            BackupZip.AddFile(modFilePath, basePath);
                        }
                    }
                }

                string backuppath = Statics.GetBackupPathForMod(Path.GetFileNameWithoutExtension(addon.ZipName));

                if (File.Exists(backuppath) && Statics.IsPathSafe(backuppath))
                    File.Delete(backuppath);

                BackupZip.Save(backuppath);
                BackupZip.Dispose();

                foreach (string file in addon.RemoveFilesList)
                {
                    string modFilePath = Path.Combine(dest, file.ToLower().Replace(addon.Destination.ToLower(), ""));
                    if (File.Exists(modFilePath) && Statics.IsPathSafe(modFilePath))
                    {
                        Debug.WriteLine("Install, removing file: " + modFilePath);
                        File.Delete(modFilePath);
                    }
                }
            }

            // We go over the files one by one so that we can ingore files as we need to
            using (ZipFile zip = ZipFile.Read(addon.ZipName))
            {
                foreach (ZipEntry file in zip)
                {
                    // Extract the files to their new home
                    // Make sure its not an ignored file
                    var hits = addon.IngoreFileList.Find(x => file.FileName.ToLower().Contains(x.ToLower()));
                    if (hits == null || hits.Length == 0 && Statics.IsPathSafe(dest))
                    {
                        file.Extract(dest, ExtractExistingFileAction.OverwriteSilently);

                        string installedPath = file.FileName;

                        if (addon.Destination != null && !installedPath.Contains(addon.Destination))
                            installedPath = Path.Combine(addon.Destination, file.FileName);

                        addon.InstalledFilesList.Add(installedPath);
                    }
                }
            }

            addon.WriteToIni(installInfoDest);

            MainView.StatusMessage = string.Format("Addon {0} Installed", addon.Name);
        }
Example #28
0
 public void Close()
 {
     zip.Dispose();
 }
Example #29
0
        /// <summary>
        /// This method generate the package as per the <c>PackageSize</c> declare.
        /// Currently <c>PackageSize</c> is 2 GB.
        /// </summary>
        /// <param name="inputFolderPath">Input folder Path.</param>
        /// <param name="outputFolderandFile">Output folder Path.</param>

        static void SplitZipFolder(string inputFolderPath, string outputFolderandFile, string threadId)
        {
            #region otherApproach

            #endregion

            int cnt = 1;
            m_packageSize = m_packageSize * 20;
            ArrayList htmlFile = new ArrayList();
            ArrayList ar       = GenerateFileList(inputFolderPath, out htmlFile); // generate file list



            // Output Zip file name.
            string outPath          = Path.Combine(outputFolderandFile, threadId + "-" + cnt + ".zip");
            long   HTMLstreamlenght = 0;

            using (ZipOutputStream oZipStream = CreateNewStream(htmlFile, outPath, out HTMLstreamlenght))
            {
                // Initialize the zip entry object.
                ZipEntry oZipEntry = new ZipEntry();

                // numbers of files in file list.
                var counter = ar.Count;
                try
                {
                    using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                    {
                        Array.Sort(ar.ToArray());            // Sort the file list array.
                        foreach (string Fil in ar.ToArray()) // for each file, generate a zip entry
                        {
                            if (!Fil.EndsWith(@"/"))         // if a file ends with '/' its a directory
                            {
                                if (!zip.ContainsEntry(Path.GetFileName(Fil.ToString())))
                                {
                                    oZipEntry = zip.AddEntry("Attachments/" + Path.GetFileName(Fil.ToString()), Fil);
                                    counter--;
                                    try
                                    {
                                        if (counter >= 0)
                                        {
                                            long      streamlenght = HTMLstreamlenght;
                                            const int BufferSize   = 4096;
                                            byte[]    obuffer      = new byte[BufferSize];
                                            if (oZipStream.Position + streamlenght < m_packageSize)
                                            {
                                                using (FileStream ostream = File.OpenRead(Fil))
                                                {
                                                    //ostream = File.OpenRead(Fil);
                                                    using (ZipOutputStream tempZStream = new ZipOutputStream(File.Create(Directory.GetCurrentDirectory() + "\\test.zip"), false))
                                                    {
                                                        tempZStream.PutNextEntry(oZipEntry.FileName);
                                                        int tempread;
                                                        while ((tempread = ostream.Read(obuffer, 0, obuffer.Length)) > 0)
                                                        {
                                                            tempZStream.Write(obuffer, 0, tempread);
                                                        }
                                                        streamlenght = tempZStream.Position;
                                                        tempZStream.Dispose();
                                                        tempZStream.Flush();
                                                        tempZStream.Close(); // close the zip stream.
                                                                             // ostream.Dispose();
                                                    }

                                                    File.Delete(Directory.GetCurrentDirectory() + "\\test.zip");
                                                }
                                            }

                                            if (oZipStream.Position + streamlenght > m_packageSize)
                                            {
                                                zip.RemoveEntry(oZipEntry);
                                                zip.Dispose();
                                                oZipStream.Dispose();
                                                oZipStream.Flush();
                                                oZipStream.Close();                                                                    // close the zip stream.
                                                cnt     = cnt + 1;
                                                outPath = Path.Combine(outputFolderandFile, threadId + "-" + cnt.ToString() + ".zip"); // create new output zip file when package size.
                                                using (ZipOutputStream oZipStream2 = CreateNewStream(htmlFile, outPath, out HTMLstreamlenght))
                                                {
                                                    oZipStream2.PutNextEntry(oZipEntry.FileName);
                                                    using (FileStream ostream = File.OpenRead(Fil))
                                                    {
                                                        int read;
                                                        while ((read = ostream.Read(obuffer, 0, obuffer.Length)) > 0)
                                                        {
                                                            oZipStream2.Write(obuffer, 0, read);
                                                        }
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                oZipStream.PutNextEntry(oZipEntry.FileName);
                                                using (FileStream ostream = File.OpenRead(Fil))
                                                {
                                                    int read;
                                                    while ((read = ostream.Read(obuffer, 0, obuffer.Length)) > 0)
                                                    {
                                                        oZipStream.Write(obuffer, 0, read);
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            Console.WriteLine("No more file existed in directory");
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.ToString());
                                        zip.RemoveEntry(oZipEntry.FileName);
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("File Existed {0} in Zip {1}", Path.GetFullPath(Fil.ToString()), outPath);
                                }
                            }
                        }
                        zip.Dispose();
                    }
                    oZipStream.Dispose();
                    oZipStream.Flush();
                    oZipStream.Close();// close stream
                }

                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                finally
                {
                    oZipStream.Dispose();
                    oZipStream.Flush();
                    oZipStream.Close();// close stream

                    Console.WriteLine("Remain Files{0}", counter);
                }
            }
        }
Example #30
0
        /// <summary>
        /// Reads a session archive zip file into an array of Session objects
        /// </summary>
        /// <param name="sFilename">Filename to load</param>
        /// <param name="bVerboseDialogs"></param>
        /// <returns>Loaded array of sessions or null, in case of failure</returns>        
        private static Session[] ReadSessionArchive(string sFilename, bool bVerboseDialogs)
        {
            /*  Okay, given the zip, we gotta:
            *		Unzip
            *		Find all matching pairs of request, response
            *		Create new Session object for each pair
            */
            if (!File.Exists(sFilename))
            {
                FiddlerApplication.Log.LogString("SAZFormat> ReadSessionArchive Failed. File " + sFilename + " does not exist.");
                return null;
            }

            ZipFile oZip = null;
            string sPassword = String.Empty;
            List<Session> outSessions = new List<Session>();

            try
            {
                // Sniff for ZIP file.
                FileStream oSniff = File.Open(sFilename, FileMode.Open, FileAccess.Read, FileShare.Read);
                if (oSniff.Length < 64 || oSniff.ReadByte() != 0x50 || oSniff.ReadByte() != 0x4B)
                {  // Sniff for 'PK'
                    FiddlerApplication.Log.LogString("SAZFormat> ReadSessionArchive Failed. " + sFilename + " is not a Fiddler-generated .SAZ archive of HTTP Sessions.");
                    oSniff.Close();
                    return null;
                }
                oSniff.Close();

                oZip = new ZipFile(sFilename);

                if (!oZip.EntryFileNames.Contains("raw/"))
                {
                    FiddlerApplication.Log.LogString("SAZFormat> ReadSessionArchive Failed. The selected ZIP is not a Fiddler-generated .SAZ archive of HTTP Sessions.");
                    return null;
                }

                foreach (ZipEntry oZE in oZip)
                {
                    // Not a request. Skip it.
                    if (!oZE.FileName.EndsWith("_c.txt") || !oZE.FileName.StartsWith("raw/")) continue;

                GetPassword:
                    if (oZE.Encryption != EncryptionAlgorithm.None && (String.Empty == sPassword)) 
                    {
                        Console.Write("Password-Protected Session Archive.\nEnter the password to decrypt, or enter nothing to abort opening.\n>");
                        sPassword = Console.ReadLine();
                        if (sPassword != String.Empty)
                        {
                            oZip.Password = sPassword;
                        }
                        else
                        {
                            return null;
                        }
                    }

                    try
                    {
                        byte[] arrRequest = new byte[oZE.UncompressedSize];
                        Stream oFS;
                        try
                        {
                            oFS = oZE.OpenReader();
                        }
                        catch (Ionic.Zip.BadPasswordException)
                        {
                            Console.WriteLine("Incorrect password.");
                            sPassword = String.Empty;
                            goto GetPassword;
                        }
                        int iRead = Utilities.ReadEntireStream(oFS, arrRequest);
                        oFS.Close();
                        Debug.Assert(iRead == arrRequest.Length, "Failed to read entire request.");

                        ZipEntry oZEResponse = oZip[oZE.FileName.Replace("_c.txt", "_s.txt")];

                        if (null == oZEResponse)
                        {
                            FiddlerApplication.Log.LogString("Could not find a server response for: " + oZE.FileName);
                            continue;
                        }

                        byte[] arrResponse = new byte[oZEResponse.UncompressedSize];
                        oFS = oZEResponse.OpenReader();
                        iRead = Utilities.ReadEntireStream(oFS, arrResponse);
                        oFS.Close();
                        Debug.Assert(iRead == arrResponse.Length, "Failed to read entire response.");

                        Session oSession = new Session(arrRequest, arrResponse);

                        ZipEntry oZEMetadata = oZip[oZE.FileName.Replace("_c.txt", "_m.xml")];

                        if (null != oZEMetadata)
                        {
                            oSession.LoadMetadata(oZEMetadata.OpenReader());
                        }
                        oSession.oFlags["x-LoadedFrom"] = oZE.FileName.Replace("_c.txt", "_s.txt");
                        outSessions.Add(oSession);
                    }
                    catch (Exception eX)
                    {
                        FiddlerApplication.Log.LogString("SAZFormat> ReadSessionArchive incomplete. Invalid data was present in session: " + oZE.FileName + ".\n\n\n" + eX.Message + "\n" + eX.StackTrace);
                    }
                }
                      /*    RetryWithPassword:
                          try
                          {
                              oFS = oRequestFile.OpenRead(FileShare.Read);
                          }
                          catch (Xceed.Zip.InvalidDecryptionPasswordException)
                          {
                            Console.WriteLine("Password-Protected Session Archive.\nEnter the password to decrypt, or enter nothing to abort opening.\n>");
                            string sPassword = Console.ReadLine();
                            if (sPassword != String.Empty)
                            {
                                oZip.DefaultDecryptionPassword = sPassword;
                                goto RetryWithPassword;
                            }

                            return null;
                          }                    
                 */
            }
            catch (Exception eX)
            {
                FiddlerApplication.ReportException(eX, "ReadSessionArchive Error");
                return null;
            }

            if (null != oZip)
            {
                oZip.Dispose();
                oZip = null;
            }

            return outSessions.ToArray();
        }
Example #31
0
        // 0 based index
        /*
         This function get the slice from the cache/drive
         */
        public Bitmap GetSliceImage(int layer)
        {
            try
            {
                if (m_mode == SFMode.eImmediate)
                {
                    if (layer == m_cachedsliceidx && m_cachedslice != null)
                    {
                        return m_cachedslice;
                    }
                    else
                    {
                        if (m_cachedslice != null)
                        {
                            m_cachedslice.Dispose();
                            m_cachedslice = null;
                        }
                        m_cachedsliceidx = layer;
                        // we're rendering slices immediately here
                        float zlev = (float)(layer * m_config.ZThick);
                        m_cachedslice = UVDLPApp.Instance().m_slicer.SliceImmediate(zlev);
                        return m_cachedslice;
                    }
                }
                else
                {
                    string path = GetSliceFilePath(modelname);
                    try
                    {

                        // try first to load from zip
                        // read the bitmap from the zip
                        m_zip = ZipFile.Read(path + ".zip");
                        string fname = Path.GetFileNameWithoutExtension(modelname) + String.Format("{0:0000}", layer) + ".png";
                        ZipEntry ze = m_zip[fname];
                        Stream stream = new MemoryStream();
                        ze.Extract(stream);
                        Bitmap bmp = new Bitmap(stream);
                        m_zip.Dispose();
                        return bmp;
                    }
                    catch (Exception)
                    {

                    }
                    try
                    {
                        //try to read bitmap from disk
                        path += UVDLPApp.m_pathsep;
                        path += Path.GetFileNameWithoutExtension(modelname) + String.Format("{0:0000}", layer) + ".png";
                        Bitmap bmp = (Bitmap)FromFile(path);
                        return bmp;
                    }
                    catch (Exception) { }
                }
                return null;
            }
            catch (Exception ex)
            {
                DebugLogger.Instance().LogRecord(ex.Message);
                return null;
            }
        }
        /// <summary>
        ///   Checks a zip file to see if its directory is consistent,
        ///   and optionally fixes the directory if necessary.
        /// </summary>
        ///
        /// <remarks>
        ///
        /// <para>
        ///   In cases of data error, the directory within a zip file can get out of
        ///   synch with the entries in the zip file.  This method checks the given
        ///   zip file, and returns true if this has occurred. It also optionally
        ///   fixes the zipfile, saving the fixed copy in <em>Name</em>_Fixed.zip.
        /// </para>
        ///
        /// <para>
        ///   This method may take a long time to run for large zip files.  It
        ///   will take even longer if the file actually needs to be fixed, and if
        ///   <c>fixIfNecessary</c> is true.
        /// </para>
        ///
        /// <para>
        ///   This method is not supported in the Reduced or Compact
        ///   Framework versions of DotNetZip.
        /// </para>
        ///
        /// </remarks>
        ///
        /// <param name="zipFileName">The filename to of the zip file to check.</param>
        ///
        /// <param name="fixIfNecessary">If true, the method will fix the zip file if
        ///     necessary.</param>
        ///
        /// <param name="writer">
        /// a TextWriter in which messages generated while checking will be written.
        /// </param>
        ///
        /// <returns>true if the named zip is OK; false if the file needs to be fixed.</returns>
        ///
        /// <seealso cref="CheckZip(string)"/>
        /// <seealso cref="FixZipDirectory(string)"/>
        public static bool CheckZip(string zipFileName, bool fixIfNecessary,
                                    TextWriter writer)

        {
            ZipFile zip1 = null, zip2 = null;
            bool isOk = true;
            try
            {
                zip1 = new ZipFile();
                zip1.FullScan = true;
                zip1.Initialize(zipFileName);

                zip2 = ZipFile.Read(zipFileName);

                foreach (var e1 in zip1)
                {
                    foreach (var e2 in zip2)
                    {
                        if (e1.FileName == e2.FileName)
                        {
                            if (e1._RelativeOffsetOfLocalHeader != e2._RelativeOffsetOfLocalHeader)
                            {
                                isOk = false;
                                if (writer != null)
                                writer.WriteLine("{0}: mismatch in RelativeOffsetOfLocalHeader  (0x{1:X16} != 0x{2:X16})",
                                                        e1.FileName, e1._RelativeOffsetOfLocalHeader,
                                                        e2._RelativeOffsetOfLocalHeader);
                            }
                            if (e1._CompressedSize != e2._CompressedSize)
                            {
                                isOk = false;
                                if (writer != null)
                                writer.WriteLine("{0}: mismatch in CompressedSize  (0x{1:X16} != 0x{2:X16})",
                                                        e1.FileName, e1._CompressedSize,
                                                        e2._CompressedSize);
                            }
                            if (e1._UncompressedSize != e2._UncompressedSize)
                            {
                                isOk = false;
                                if (writer != null)
                                writer.WriteLine("{0}: mismatch in UncompressedSize  (0x{1:X16} != 0x{2:X16})",
                                                        e1.FileName, e1._UncompressedSize,
                                                        e2._UncompressedSize);
                            }
                            if (e1.CompressionMethod != e2.CompressionMethod)
                            {
                                isOk = false;
                                if (writer != null)
                                writer.WriteLine("{0}: mismatch in CompressionMethod  (0x{1:X4} != 0x{2:X4})",
                                                        e1.FileName, e1.CompressionMethod,
                                                        e2.CompressionMethod);
                            }
                            if (e1.Crc != e2.Crc)
                            {
                                isOk = false;
                                if (writer != null)
                                writer.WriteLine("{0}: mismatch in Crc32  (0x{1:X4} != 0x{2:X4})",
                                                        e1.FileName, e1.Crc,
                                                        e2.Crc);
                            }

                            // found a match, so stop the inside loop
                            break;
                        }
                    }
                }

                zip2.Dispose();
                zip2 = null;

                if (!isOk && fixIfNecessary)
                {
                    string newFileName = Path.GetFileNameWithoutExtension(zipFileName);
                    newFileName = System.String.Format("{0}_fixed.zip", newFileName);
                    zip1.Save(newFileName);
                }
            }
            finally
            {
                if (zip1 != null) zip1.Dispose();
                if (zip2 != null) zip2.Dispose();
            }
            return isOk;
        }
        protected void Button1_Click(object sender, System.EventArgs e)
        {
            string loc = ConfigurationManager.AppSettings["transitLocation"].ToString();
            string arch = ConfigurationManager.AppSettings["transitArchive"].ToString();
            string appRoot = HttpRuntime.AppDomainAppPath;
            string transitDirectory = loc.Replace("~/", appRoot);
            System.IO.StreamWriter agencyRecord, feedInfoRecord, routesRecord, stopsRecord, calendarsRecord, calendarDatesRecord, tripsRecord, stopTimesRecord, fareAttributesRecord, fareRulesRecord, testingRecord;

            // Set the message text back to nothing
            message.Text = " ";

            // Create root variables
            int agencyRoot;
            int routesRoot;
            int servicesRoot;
            int exceptionsRoot;
            int stopsRoot;
            int tripsRoot;
            int faresRoot;

            // Create an Error Counter
            int errors = 0;

            // Check to see if each of the txt files exist. If they don't then create them
            if (!System.IO.File.Exists(transitDirectory + "\\agency.txt"))
            {
                System.IO.File.Create(transitDirectory + "\\agency.txt");
            }
            if (!System.IO.File.Exists(transitDirectory + "\\feed_info.txt"))
            {
                System.IO.File.Create(transitDirectory + "\\feed_info.txt");
            }
            if (!System.IO.File.Exists(transitDirectory + "\\routes.txt"))
            {
                System.IO.File.Create(transitDirectory + "\\routes.txt");
            }
            if (!System.IO.File.Exists(transitDirectory + "\\stops.txt"))
            {
                System.IO.File.Create(transitDirectory + "\\stops.txt");
            }
            if (!System.IO.File.Exists(transitDirectory + "\\calendar.txt"))
            {
                System.IO.File.Create(transitDirectory + "\\calendar.txt");
            }
            if (!System.IO.File.Exists(transitDirectory + "\\calendar_dates.txt"))
            {
                System.IO.File.Create(transitDirectory + "\\calendar_dates.txt");
            }
            if (!System.IO.File.Exists(transitDirectory + "\\trips.txt"))
            {
                System.IO.File.Create(transitDirectory + "\\trips.txt");
            }
            if (!System.IO.File.Exists(transitDirectory + "\\stop_times.txt"))
            {
                System.IO.File.Create(transitDirectory + "\\stop_times.txt");
            }
            if (!System.IO.File.Exists(transitDirectory + "\\fare_attributes.txt"))
            {
                System.IO.File.Create(transitDirectory + "\\fare_attributes.txt");
            }
            if (!System.IO.File.Exists(transitDirectory + "\\fare_rules.txt"))
            {
                System.IO.File.Create(transitDirectory + "\\fare_rules.txt");
            }
            if (!System.IO.File.Exists(transitDirectory + "\\testing.txt"))
            {
                System.IO.File.Create(transitDirectory + "\\testing.txt");
            }

            try
            {
                // Create StreamWriters for each of the txt Records
                agencyRecord = new StreamWriter(transitDirectory + "\\agency.txt");
                feedInfoRecord = new StreamWriter(transitDirectory + "\\feed_info.txt");
                routesRecord = new StreamWriter(transitDirectory + "\\routes.txt");
                stopsRecord = new StreamWriter(transitDirectory + "\\stops.txt");
                calendarsRecord = new StreamWriter(transitDirectory + "\\calendar.txt");
                calendarDatesRecord = new StreamWriter(transitDirectory + "\\calendar_dates.txt");
                tripsRecord = new StreamWriter(transitDirectory + "\\trips.txt");
                stopTimesRecord = new StreamWriter(transitDirectory + "\\stop_times.txt");
                fareAttributesRecord = new StreamWriter(transitDirectory + "\\fare_attributes.txt");
                fareRulesRecord = new StreamWriter(transitDirectory + "\\fare_rules.txt");
                testingRecord = new StreamWriter(transitDirectory + "\\testing.txt");

                // Write the first line of each txt file
                agencyRecord.WriteLine("agency_id,agency_name,agency_url,agency_timezone,agency_lang,agency_phone,agency_fare_url");
                feedInfoRecord.WriteLine("feed_publisher_name,feed_publisher_url,feed_lang,feed_version");
                routesRecord.WriteLine("route_id,agency_id,route_short_name,route_long_name,route_desc,route_type,route_url,route_color,route_text_color");
                stopsRecord.WriteLine("stop_id,stop_code,stop_name,stop_desc,stop_lat,stop_lon,zone_id,stop_url,location_type,parent_station");
                calendarsRecord.WriteLine("service_id,monday,tuesday,wednesday,thursday,friday,saturday,sunday,start_date,end_date");
                calendarDatesRecord.WriteLine("service_id,date,exception_type");
                tripsRecord.WriteLine("route_id,service_id,trip_id,trip_headsign,direction_id,block_id,shape_id");
                stopTimesRecord.WriteLine("trip_id,arrival_time,departure_time,stop_id,stop_sequence,stop_headsign,pickup_type,drop_off_type,shape_dist_traveled");
                fareAttributesRecord.WriteLine("fare_id,price,currency_type,payment_method,transfers,transfer_duration");
                fareRulesRecord.WriteLine("fare_id,route_id,origin_id,destination_id,contains_id");

                // Connect to the SQL Database
                SqlConnection SQLConn = new SqlConnection(GlobalSettings.DbDSN);
                SQLConn.Open();
                SqlDataAdapter dataAdapter;
                DataTableReader dataReader;

                // Connect to the SQL database for the Routes node
                string agencySQL = string.Format(@"select id from umbracoNode where text = 'Routes'");
                dataAdapter = new SqlDataAdapter(agencySQL, SQLConn);
                DataSet agencyDataSet = new DataSet();
                dataAdapter.Fill(agencyDataSet);

                // Connect to the SQL database for the Transit Routes node
                string routesSQL = string.Format(@"select id from umbracoNode where text = 'Transit Routes'");
                dataAdapter = new SqlDataAdapter(routesSQL, SQLConn);
                DataSet routesDataSet = new DataSet();
                dataAdapter.Fill(routesDataSet);

                // Connect to the SQL database for the Transit Service Calendars node
                string servicesSQL = string.Format(@"select id from umbracoNode where text = 'Transit Service Calendars'");
                dataAdapter = new SqlDataAdapter(servicesSQL, SQLConn);
                DataSet servicesDataSet = new DataSet();
                dataAdapter.Fill(servicesDataSet);

                // Connect to the SQL database for the Transit Service Calendar Exceptions node
                string exceptionsSQL = string.Format(@"select id from umbracoNode where text = 'Transit Service Calendar Exceptions'");
                dataAdapter = new SqlDataAdapter(exceptionsSQL, SQLConn);
                DataSet exceptionsDataSet = new DataSet();
                dataAdapter.Fill(exceptionsDataSet);

                // Connect to the SQL database for the Transit Stops node
                string stopsSQL = string.Format(@"select id from umbracoNode where text = 'Transit Stops'");
                dataAdapter = new SqlDataAdapter(stopsSQL, SQLConn);
                DataSet stopsDataSet = new DataSet();
                dataAdapter.Fill(stopsDataSet);

                // Connect to the SQL database for the Transit Trips node
                string tripsSQL = string.Format(@"select id from umbracoNode where text = 'Transit Trips and Stop Times'");
                dataAdapter = new SqlDataAdapter(tripsSQL, SQLConn);
                DataSet tripsDataSet = new DataSet();
                dataAdapter.Fill(tripsDataSet);

                // Connect to the SQL database for the Transit Fares node
                string faresSQL = string.Format(@"select id from umbracoNode where text = 'Transit Fares'");
                dataAdapter = new SqlDataAdapter(faresSQL, SQLConn);
                DataSet faresDataSet = new DataSet();
                dataAdapter.Fill(faresDataSet);

                // Close and dispose SQL connection
                SQLConn.Close();
                SQLConn.Dispose();

                // Set the data reader for the Routes node and set the ID for the Routes node
                dataReader = agencyDataSet.CreateDataReader();
                if (dataReader.Read()) { agencyRoot = (int)dataReader["id"]; } else { status.Text = "No Routes Folder Found!"; return; }

                // Set the data reader for the Transit Routes node and set the ID for the Transit Routes node
                dataReader = routesDataSet.CreateDataReader();
                if (dataReader.Read()) { routesRoot = (int)dataReader["id"]; } else { status.Text = "No Transit Routes Folder Found!"; return; }

                // Set the data reader for the Transit Service Calendars node and set the ID for the Transit Service Calendars node
                dataReader = servicesDataSet.CreateDataReader();
                if (dataReader.Read()) { servicesRoot = (int)dataReader["id"]; } else { status.Text = "No Transit Service Calendars Folder Found!"; return; }

                // Set the data reader for the Transit Service Calendars Exceptions node and set the ID for the Transit Service Calendars Exceptions node
                dataReader = exceptionsDataSet.CreateDataReader();
                if (dataReader.Read()) { exceptionsRoot = (int)dataReader["id"]; } else { status.Text = "No Transit Service Calendar Exceptions Folder Found!"; return; }

                // Set the data reader for the Transit Stops node and set the ID for the Transit Stops node
                dataReader = stopsDataSet.CreateDataReader();
                if (dataReader.Read()) { stopsRoot = (int)dataReader["id"]; } else { status.Text = "No Transit Stops Folder Found!"; return; }

                // Set the data reader for the Transit Trips node and set the ID for the Transit Trips and Stop Times node
                dataReader = tripsDataSet.CreateDataReader();
                if (dataReader.Read()) { tripsRoot = (int)dataReader["id"]; } else { status.Text = "No Transit Trips and Stop Times Folder Found!"; return; }

                // Set the data reader for the Transit Fares node and set the ID for the Transit Fares node
                dataReader = faresDataSet.CreateDataReader();
                if (dataReader.Read()) { faresRoot = (int)dataReader["id"]; } else { status.Text = "No Transit Fares Folder Found!"; return; }

                // Dispose dataReader
                dataReader.Dispose();

                // Get the agency.txt information from the Routes node and write it to agencyRecord
                Document agency = new Document(agencyRoot);
                // Create URL out of agency fare page id
                string fareURL = new Node(Convert.ToInt32(agency.getProperty("agencyFarePage").Value.ToString())).NiceUrl;
                agencyRecord.WriteLine(agency.getProperty("agencyID").Value.ToString() + "," + agency.getProperty("agencyName").Value.ToString().Replace(",", " ") + "," + agency.getProperty("agencyURL").Value.ToString() + "," + agency.getProperty("agencyTimezone").Value.ToString() + ",EN," + agency.getProperty("agencyPhoneNumber").Value.ToString() + "," + agency.getProperty("agencyURL").Value.ToString() + fareURL);
                // Testing
                testingRecord.WriteLine("agency.txt");
                testingRecord.WriteLine("agency_id = " + agency.getProperty("agencyID").Value.ToString() + "  |  agency_name = " + agency.getProperty("agencyName").Value.ToString().Replace(",", " ") + "  |  agency_url = " + agency.getProperty("agencyURL").Value.ToString() + "  |  agency_timezone = " + agency.getProperty("agencyTimezone").Value.ToString() + "  |  agency_lang = EN  |  agency_phone = " + agency.getProperty("agencyPhoneNumber").Value.ToString() + "  |  agency_fare_url = " + agency.getProperty("agencyURL").Value.ToString() + fareURL);
                testingRecord.WriteLine("");

                // Write the only line for feed_info.txt
                feedInfoRecord.WriteLine("HillSouth,http://hillsouth.com,EN,");
                // Testing
                testingRecord.WriteLine("feed_info.txt");
                testingRecord.WriteLine("feed_publisher_name = HillSouth  |  feed_publisher_url = http://hillsouth.com  |  feed_lang = EN  |  feed_version =  ");
                testingRecord.WriteLine("");

                // Get the routes.txt information from the Transit Routes children nodes and write it to routesRecord
                Document[] routes = new Document(routesRoot).Children;
                // Testing
                testingRecord.WriteLine("routes.txt");
                for (int a = 0; a < routes.Length; a++)
                {
                    // Send the route to XML
                    XmlNode routesNode = routes[a].ToXml(new XmlDocument(), false);
                    // Check to see if the routesNode equals null, if so, the route is not published
                    string routeNodeName;
                    if (routesNode == null)
                    {
                        continue;
                    }
                    else
                    {
                        // Get the route node name from the xml node attributes
                        routeNodeName = routesNode.Attributes.GetNamedItem("nodeName").Value.ToString();
                    }
                    // Check to see if the Route needs to be excludes due to the googleTransitOverride
                    string googleTransitOverride = routes[a].getProperty("googleTransitOverride").Value.ToString();
                    if (googleTransitOverride == "1")
                    {
                        message.Text = message.Text + "&#8226; <span style='color: red;'>Route <b>" + routeNodeName + "</b> has not been added to the Google Transit Feed.</span><br />";
                        continue;
                    }
                    // Write the needed line
                    routesRecord.WriteLine(routeNodeName + ",," + routes[a].getProperty("routeShortName").Value.ToString().Replace(",", " ") + "," + routes[a].getProperty("routeFullName").Value.ToString().Replace(",", " ") + "," + routes[a].getProperty("routeDescription").Value.ToString().Replace(",", " ") + ",3,,,");
                    // Testing
                    testingRecord.WriteLine("route_id = " + routeNodeName + "  |  agency_id =  |  route_short_name = " + routes[a].getProperty("routeShortName").Value.ToString().Replace(",", " ") + "  |  route_long_name = " + routes[a].getProperty("routeFullName").Value.ToString().Replace(",", " ") + "  |  route_description = " + routes[a].getProperty("routeDescription").Value.ToString().Replace(",", " ") + "  |  route_type = 3  |  route_url =  |  route_color =  |  route_text_color = ");
                }
                // Testing
                testingRecord.WriteLine("");

                // Get the stops.txt information from the Transit Stops children nodes and write it to stopsRecord
                Document[] stops = new Document(stopsRoot).Children;
                // Testing
                testingRecord.WriteLine("stops.txt");
                for (int b = 0; b < stops.Length; b++)
                {
                    // Send the stop to XML
                    XmlNode stopsNode = stops[b].ToXml(new XmlDocument(), false);
                    // Check to see if the stopsNode equals null, if so, the stop is not published
                    string stopNodeName;
                    if (stopsNode == null)
                    {
                        continue;
                    }
                    else
                    {
                        // Get the stop node name from the xml node attributes
                        stopNodeName = stopsNode.Attributes.GetNamedItem("nodeName").Value.ToString();
                    }
                    // Create stopCoordinates variable
                    string[] stopCoordinates;
                    // Check to see whether or not stopMap has been populated
                    if (String.IsNullOrEmpty(stops[b].getProperty("stopMap").Value.ToString()))
                    {
                        message.Text = message.Text + "&#8226; <span style='color: red;'>Stop <b>" + stopNodeName + "</b> has not been mapped correctly.</span><br />";
                        errors++;
                        continue;
                    }
                    else
                    {
                        stopCoordinates = stops[b].getProperty("stopMap").Value.ToString().Split(',');
                    }
                    // Check to see whether or not stopZone has been populated
                    if (stops[b].getProperty("stopZone").Value.ToString() == "-1")
                    {
                        message.Text = message.Text + "&#8226; <span style='color: red;'>Stop <b>" + stopNodeName + "</b> does not have a stop zone applied to it.</span><br />";
                        errors++;
                        continue;
                    }
                    // Write the information
                    stopsRecord.WriteLine(stopNodeName + ",," + stops[b].getProperty("stopName").Value.ToString().Replace(",", " ") + "," + stops[b].getProperty("stopDescription").Value.ToString().Replace(",", " ") + "," + stopCoordinates[0] + "," + stopCoordinates[1] + "," + stops[b].getProperty("stopZone").Value.ToString() + ",,,");
                    // Testing
                    testingRecord.WriteLine("stop_id = " + stopNodeName + "  |  stop_code =  |  stop_name = " + stops[b].getProperty("stopName").Value.ToString().Replace(",", " ") + "  |  stop_desc = " + stops[b].getProperty("stopDescription").Value.ToString().Replace(",", " ") + "  |  stop_lat = " + stopCoordinates[0] + "  |  stop_lon = " + stopCoordinates[1] + "  |  zone_id = " + stops[b].getProperty("stopZone").Value.ToString() + "  |  stop_url =  |  location_type =  |  parent_station = ");
                }
                // Testing
                testingRecord.WriteLine("");

                // Get the calendar.txt information from the Transit Service Calendars children nodes and write it to calendarsRecord
                Document[] services = new Document(servicesRoot).Children;
                // Testing
                testingRecord.WriteLine("calendar.txt");
                for (int c = 0; c < services.Length; c++)
                {
                    // Send the calendar to XML
                    XmlNode servicesNode = services[c].ToXml(new XmlDocument(), false);
                    // Check to see if the servicesNode equals null, if so, the exception is not published
                    string serviceNodeName;
                    if (servicesNode == null)
                    {
                        continue;
                    }
                    else
                    {
                        // Get the calendar node name from the xml node attributes
                        serviceNodeName = servicesNode.Attributes.GetNamedItem("nodeName").Value.ToString();
                    }
                    // Check to see if the service calendar has at least one day selected
                    if (services[c].getProperty("serviceMonday").Value.ToString() == "0" && services[c].getProperty("serviceTuesday").Value.ToString() == "0" && services[c].getProperty("serviceWednesday").Value.ToString() == "0" && services[c].getProperty("serviceThursday").Value.ToString() == "0" && services[c].getProperty("serviceFriday").Value.ToString() == "0" && services[c].getProperty("serviceSaturday").Value.ToString() == "0" && services[c].getProperty("serviceSunday").Value.ToString() == "0")
                    {
                        message.Text = message.Text + "&#8226; <span style='color: red;'>Service Calendar <b>" + serviceNodeName + "</b> does not have any days chosen. A Service Calendar must have at least one day chosen.</span><br />";
                        errors++;
                        continue;
                    }
                    // Write the information
                    calendarsRecord.WriteLine(serviceNodeName + "," + services[c].getProperty("serviceMonday").Value.ToString() + "," + services[c].getProperty("serviceTuesday").Value.ToString() + "," + services[c].getProperty("serviceWednesday").Value.ToString() + "," + services[c].getProperty("serviceThursday").Value.ToString() + "," + services[c].getProperty("serviceFriday").Value.ToString() + "," + services[c].getProperty("serviceSaturday").Value.ToString() + "," + services[c].getProperty("serviceSunday").Value.ToString() + "," + services[c].getProperty("serviceStartDate").Value.ToString().Substring(6, 4) + services[c].getProperty("serviceStartDate").Value.ToString().Substring(3, 2) + services[c].getProperty("serviceStartDate").Value.ToString().Substring(0, 2) + "," + services[c].getProperty("serviceEndDate").Value.ToString().Substring(6, 4) + services[c].getProperty("serviceEndDate").Value.ToString().Substring(3, 2) + services[c].getProperty("serviceEndDate").Value.ToString().Substring(0, 2));
                    // Testing
                    testingRecord.WriteLine("service_id = " + serviceNodeName + "  |  monday = " + services[c].getProperty("serviceMonday").Value.ToString() + "  |  tuesday = " + services[c].getProperty("serviceTuesday").Value.ToString() + "  |  wednesday = " + services[c].getProperty("serviceWednesday").Value.ToString() + "  |  thursday = " + services[c].getProperty("serviceThursday").Value.ToString() + "  |  friday = " + services[c].getProperty("serviceFriday").Value.ToString() + "  |  saturday = " + services[c].getProperty("serviceSaturday").Value.ToString() + "  |  sunday = " + services[c].getProperty("serviceSunday").Value.ToString() + "  |  start_date = " + services[c].getProperty("serviceStartDate").Value.ToString().Substring(6, 4) + services[c].getProperty("serviceStartDate").Value.ToString().Substring(3, 2) + services[c].getProperty("serviceStartDate").Value.ToString().Substring(0, 2) + "  |  end_date = " + services[c].getProperty("serviceEndDate").Value.ToString().Substring(6, 4) + services[c].getProperty("serviceEndDate").Value.ToString().Substring(3, 2) + services[c].getProperty("serviceEndDate").Value.ToString().Substring(0, 2));
                }
                // Testing
                testingRecord.WriteLine("");

                // Get the calendar_dates.txt information from the Transit Service Calendar Exceptions children nodes and write it to calendarDatesRecord
                Document[] exceptions = new Document(exceptionsRoot).Children;
                // Testing
                testingRecord.WriteLine("calendar_dates.txt");
                for (int d = 0; d < exceptions.Length; d++)
                {
                    // Send the calendar exception to XML
                    XmlNode exceptionsNode = exceptions[d].ToXml(new XmlDocument(), false);
                    // Check to see if the exceptionsNode equals null, if so, the exception is not published
                    string exceptionNodeName;
                    if (exceptionsNode == null)
                    {
                        continue;
                    }
                    else
                    {
                        // Get the calendar exception node name from the xml node attributes
                        exceptionNodeName = exceptionsNode.Attributes.GetNamedItem("nodeName").Value.ToString();
                    }
                    // Check to see if the calendar exception has the removeService option selected
                    if (exceptions[d].getProperty("removeService").Value.ToString() == "-1")
                    {
                        message.Text = message.Text + "&#8226; <span style='color: red;'>Service Calendar Exception <b>" + exceptionNodeName + "</b> does not have a value for Remove Service. To create an exception, you must choose to remove a service.</span><br />";
                        errors++;
                        continue;
                    }
                    // Check to see if the calendar exception has the addService option selected
                    if (exceptions[d].getProperty("addService").Value.ToString() == "-1")
                    {
                        message.Text = message.Text + "&#8226; <span style='color: red;'>Service Calendar Exception <b>" + exceptionNodeName + "</b> does not have a value for Add Service. To create an exception, you must choose to add a service.</span><br />";
                        errors++;
                        continue;
                    }
                    // Check to see if the calendar exception's removeService and addService options are the same, if so pass error
                    if (exceptions[d].getProperty("removeService").Value.ToString() == exceptions[d].getProperty("addService").Value.ToString())
                    {
                        message.Text = message.Text + "&#8226; <span style='color: red;'>Service Calendar Exception <b>" + exceptionNodeName + "</b> has the same value for its Remove Service and Add Service options. The two options have to be different.</span><br />";
                        errors++;
                        continue;
                    }
                    // Write the first line which is the remove service line
                    calendarDatesRecord.WriteLine(exceptions[d].getProperty("removeService").Value.ToString() + "," + exceptions[d].getProperty("exceptionDate").Value.ToString().Substring(6, 4) + exceptions[d].getProperty("exceptionDate").Value.ToString().Substring(3, 2) + exceptions[d].getProperty("exceptionDate").Value.ToString().Substring(0, 2) + ",2");
                    // Write the second line which is the add service line
                    calendarDatesRecord.WriteLine(exceptions[d].getProperty("addService").Value.ToString() + "," + exceptions[d].getProperty("exceptionDate").Value.ToString().Substring(6, 4) + exceptions[d].getProperty("exceptionDate").Value.ToString().Substring(3, 2) + exceptions[d].getProperty("exceptionDate").Value.ToString().Substring(0, 2) + ",1");
                    // Testing
                    testingRecord.WriteLine("service_id = " + exceptions[d].getProperty("removeService").Value.ToString() + "  |  date = " + exceptions[d].getProperty("exceptionDate").Value.ToString().Substring(6, 4) + exceptions[d].getProperty("exceptionDate").Value.ToString().Substring(3, 2) + exceptions[d].getProperty("exceptionDate").Value.ToString().Substring(0, 2) + "  |  exception_type = 2");
                    testingRecord.WriteLine("service_id = " + exceptions[d].getProperty("addService").Value.ToString() + "  |  date = " + exceptions[d].getProperty("exceptionDate").Value.ToString().Substring(6, 4) + exceptions[d].getProperty("exceptionDate").Value.ToString().Substring(3, 2) + exceptions[d].getProperty("exceptionDate").Value.ToString().Substring(0, 2) + "  |  exception_type = 1");
                }
                // Testing
                testingRecord.WriteLine("");

                // Get the trips.txt information from the Transit Trips children nodes and write it to the tripsRecord
                Document[] trips = new Document(tripsRoot).Children;
                // Create the DataSet
                DataSet set = new DataSet("Trip_Stop_Times");
                // Loop through all trips and stop times and put them in a DataSet for using when a trip is based on another
                using (set)
                {
                    for (int m = 0; m < trips.Length; m++)
                    {
                        // Send the trip to XML
                        XmlNode tripsNode = trips[m].ToXml(new XmlDocument(), false);
                        // Check to see if the tripsNode equals null, if so, the trip is not published
                        string tripNodeName;
                        if (tripsNode == null)
                        {
                            continue;
                        }
                        else
                        {
                            // Get the trip node name from the xml node attributes
                            tripNodeName = tripsNode.Attributes.GetNamedItem("nodeName").Value.ToString();
                        }
                        // Check to see if the trip has a route selected
                        if (trips[m].getProperty("route").Value.ToString() == "-1")
                        {
                            continue;
                        }
                        // Check to see if the trip has a calendar selected
                        if (trips[m].getProperty("calendar").Value.ToString() == "-1")
                        {
                            continue;
                        }
                        // Create a table for this trip
                        DataTable table1 = new DataTable(tripNodeName);
                        table1.Columns.Add("tripHeadway");
                        table1.Columns.Add("stop_id");
                        table1.Columns.Add("arrival_time");
                        table1.Columns.Add("departure_time");
                        // Set the trip's stop times to a variable
                        Document[] stopTimes = trips[m].Children;
                        for (int n = 0; n < stopTimes.Length; n++)
                        {
                            // Send the stop time to XML
                            XmlNode stopTimesNode = stopTimes[n].ToXml(new XmlDocument(), false);
                            // Check to see if the stopTimesNode equals null, if so, the stop time is not published
                            string stopTimeNodeName;
                            if (stopTimesNode == null)
                            {
                                continue;
                            }
                            else
                            {
                                // Get the stop time node name from the xml node attributes
                                stopTimeNodeName = stopTimesNode.Attributes.GetNamedItem("nodeName").Value.ToString();
                            }
                            // Check to see if a stop has been selected
                            if (stopTimes[n].getProperty("transitStop").Value.ToString() == "-1")
                            {
                                continue;
                            }
                            // Check to see if a departure time has been given, if not set the departure time to the arrival time
                            string arrivalTime = stopTimes[n].getProperty("arrivalTime").Value.ToString();
                            string departureTime = stopTimes[n].getProperty("departureTime").Value.ToString();
                            if (String.IsNullOrEmpty(departureTime))
                            {
                                departureTime = arrivalTime;
                            }
                            // Create the DataTable row with the correct information for the columns
                            if (String.IsNullOrEmpty(trips[m].getProperty("tripHeadway").Value.ToString()))
                            {
                                table1.Rows.Add(null, stopTimes[n].getProperty("transitStop").Value.ToString(), arrivalTime, departureTime);
                            }
                            else
                            {
                                table1.Rows.Add(trips[m].getProperty("tripHeadway").Value.ToString(), stopTimes[n].getProperty("transitStop").Value.ToString(), arrivalTime, departureTime);
                            }
                        }
                        // Add the DataTables to the DataSet
                        set.Tables.Add(table1);
                    }
                }
                // Testing
                testingRecord.WriteLine("trips.txt");
                // Loop through and do all of the work
                for (int f = 0; f < trips.Length; f++)
                {
                    // Send the trip to XML
                    XmlNode tripsNode = trips[f].ToXml(new XmlDocument(), false);
                    // Check to see if the tripsNode equals null, if so, the trip is not published
                    string tripNodeName;
                    if (tripsNode == null)
                    {
                        continue;
                    }
                    else
                    {
                        // Get the trip node name from the xml node attributes
                        tripNodeName = tripsNode.Attributes.GetNamedItem("nodeName").Value.ToString();
                    }
                    // Check to see if the trip has a route selected
                    if (trips[f].getProperty("route").Value.ToString() == "-1")
                    {
                        message.Text = message.Text + "&#8226; <span style='color: red;'>Trip <b>" + tripNodeName + "</b> does not have a route selected.</span><br />";
                        errors++;
                        continue;
                    }
                    // Check to see if the trip has a calendar selected
                    if (trips[f].getProperty("calendar").Value.ToString() == "-1")
                    {
                        message.Text = message.Text + "&#8226; <span style='color: red;'>Trip <b>" + tripNodeName + "</b> does not have a calendar selected.</span><br />";
                        errors++;
                        continue;
                    }
                    // Set the direction of the trip if it has been given a value
                    string direction;
                    if (String.IsNullOrEmpty(trips[f].getProperty("tripDirection").Value.ToString()))
                    {
                        direction = "";
                    }
                    else
                    {
                        if (trips[f].getProperty("tripDirection").Value.ToString() == "96" || trips[f].getProperty("tripDirection").Value.ToString() == "57")
                        {
                            direction = "0";
                        }
                        else
                        {
                            direction = "1";
                        }
                    }
                    // Testing
                    // message.Text = message.Text + "&#8226; <span style='color: red;'>Trip <b>" + tripNodeName + "</b> direction is: " + trips[f].getProperty("tripDirection").Value.ToString() + ".</span><br />";
                    // Set the trip's stop times to a variable
                    Document[] stopTimes = trips[f].Children;
                    // Check to see if the current trip is based on another.
                    if (trips[f].getProperty("tripBasedOn").Value.ToString() == "-1")
                    {
                        // The trip is not based on another, check to see if there are any stopTimes. If not, is it possible that they accidently meant to base it off of another
                        if (stopTimes.Length == 0)
                        {
                            message.Text = message.Text + "&#8226; <span style='color: red;'>Trip <b>" + tripNodeName + "</b> does not have any stop times provided. Did you mean to base it off of another trip and didn't?</span><br />";
                            errors++;
                            continue;
                        }
                        // Check to see if there is a tripHeadway
                        if (String.IsNullOrEmpty(trips[f].getProperty("tripHeadway").Value.ToString()))
                        {
                            // There is not a tripHeadway, write out the trip
                            tripsRecord.WriteLine(trips[f].getProperty("route").Value.ToString() + "," + trips[f].getProperty("calendar").Value.ToString() + "," + tripNodeName + "," + trips[f].getProperty("tripHeadsign").Value.ToString().Replace(",", " ") + "," + direction + ",,");
                            // Testing
                            testingRecord.WriteLine("");
                            testingRecord.WriteLine("route_id = " + trips[f].getProperty("route").Value.ToString() + "  |  service_id = " + trips[f].getProperty("calendar").Value.ToString() + "  |  trip_id = " + tripNodeName + "  |  trip_headsign = " + trips[f].getProperty("tripHeadsign").Value.ToString().Replace(",", " ") + "  |  direction_id = " + direction + "  |  block_id =  |  shape_id = ");
                            // Loop through each of the stop times and write to the stopTimesRecord
                            for (int g = 0; g < stopTimes.Length; g++)
                            {
                                // Send the stop time to XML
                                XmlNode stopTimesNode = stopTimes[g].ToXml(new XmlDocument(), false);
                                // Check to see if the stopTimesNode equals null, if so, the stop time is not published
                                string stopTimeNodeName;
                                if (stopTimesNode == null)
                                {
                                    continue;
                                }
                                else
                                {
                                    // Get the stop time node name from the xml node attributes
                                    stopTimeNodeName = stopTimesNode.Attributes.GetNamedItem("nodeName").Value.ToString();
                                }
                                // Check to see if a stop has been selected
                                if (stopTimes[g].getProperty("transitStop").Value.ToString() == "-1")
                                {
                                    message.Text = message.Text + "&#8226; <span style='color: red;'>Stop Time <b>" + stopTimeNodeName + "</b> does not have a stop selected.</span><br />";
                                    errors++;
                                    continue;
                                }
                                // Check to see if a departure time has been given, if not set the departure time to the arrival time
                                string arrivalTime = stopTimes[g].getProperty("arrivalTime").Value.ToString();
                                string departureTime = stopTimes[g].getProperty("departureTime").Value.ToString();
                                if (String.IsNullOrEmpty(departureTime))
                                {
                                    departureTime = arrivalTime;
                                }
                                // Write out the stop times
                                stopTimesRecord.WriteLine(tripNodeName + "," + arrivalTime + "," + departureTime + "," + stopTimes[g].getProperty("transitStop").Value.ToString() + "," + (g + 1) + ",,0,0,");
                                // Testing
                                testingRecord.WriteLine("     stop_times.txt:  trip_id = " + tripNodeName + "  |  arrival_time = " + arrivalTime + "  |  departure_time = " + departureTime + "  |  stop_id = " + stopTimes[g].getProperty("transitStop").Value.ToString() + "  |  stop_sequence = " + (g + 1) + "  |  stop_headsign =  |  pickup_type = 0  |  drop_off_type = 0  |  shape_dist_traveled = ");
                            }
                        }
                        else
                        {
                            // There is a tripHeadway
                            // Check to make sure that there is a calendarStartTime and calendarEndTime
                            if (String.IsNullOrEmpty(trips[f].getProperty("calendarStartTime").Value.ToString()) || String.IsNullOrEmpty(trips[f].getProperty("calendarEndTime").Value.ToString()))
                            {
                                message.Text = message.Text + "&#8226; <span style='color: red;'>Trip <b>" + tripNodeName + "</b> has a Trip Headway provided, but does not have a Calendar Start Time or Calendar End Time provided.</span><br />";
                                errors++;
                                continue;
                            }
                            // Create DateTime objects out of the present CalendarStartTime and CalendarEndTime
                            DateTime calendarStartTime = new DateTime(2011, 1, 1, Convert.ToInt32(trips[f].getProperty("calendarStartTime").Value.ToString().Substring(0, 2)), Convert.ToInt32(trips[f].getProperty("calendarStartTime").Value.ToString().Substring(3, 2)), Convert.ToInt32(trips[f].getProperty("calendarStartTime").Value.ToString().Substring(6, 2)));
                            DateTime calendarEndTime = new DateTime(2011, 1, 1, Convert.ToInt32(trips[f].getProperty("calendarEndTime").Value.ToString().Substring(0, 2)), Convert.ToInt32(trips[f].getProperty("calendarEndTime").Value.ToString().Substring(3, 2)), Convert.ToInt32(trips[f].getProperty("calendarEndTime").Value.ToString().Substring(6, 2)));
                            // Find the nextStartTime
                            string lastTime;
                            if (String.IsNullOrEmpty(stopTimes[stopTimes.Length - 1].getProperty("departureTime").Value.ToString()))
                            {
                                lastTime = stopTimes[stopTimes.Length - 1].getProperty("arrivalTime").Value.ToString();
                            }
                            else
                            {
                                lastTime = stopTimes[stopTimes.Length - 1].getProperty("departureTime").Value.ToString();
                            }
                            DateTime lastStopTime = new DateTime(2011, 1, 1, Convert.ToInt32(lastTime.Substring(0, 2)), Convert.ToInt32(lastTime.Substring(3, 2)), Convert.ToInt32(lastTime.Substring(6, 2)));
                            // Create a double variable out of the tripHeadway
                            double headway = Convert.ToInt32(trips[f].getProperty("tripHeadway").Value.ToString());
                            // Add the tripHeadway to the nextStartTime to get the real nextStartTime
                            DateTime nextStartTime = lastStopTime.AddSeconds(headway);
                            // Find the hour difference between the nextStartTime and all of the stopTimes
                            string arrivalTime;
                            string departureTime;
                            int stopTimeHour;
                            int nextStartTimeHour = Convert.ToInt32(nextStartTime.ToString("HH"));
                            int[] hourDifferences = new int[stopTimes.Length];
                            // Testing
                            // testingRecord.WriteLine("");
                            // testingRecord.WriteLine("Stop Time Information:");
                            for (int h = 0; h < stopTimes.Length; h++)
                            {
                                // Send the stop time to XML
                                XmlNode stopTimesNode = stopTimes[h].ToXml(new XmlDocument(), false);
                                // Check to see if a departureTime has been given, if not, set the departureTime to the arrivalTime
                                arrivalTime = stopTimes[h].getProperty("arrivalTime").Value.ToString();
                                departureTime = stopTimes[h].getProperty("departureTime").Value.ToString();
                                if (String.IsNullOrEmpty(departureTime))
                                {
                                    departureTime = arrivalTime;
                                }
                                // Assign the stopTimeHour
                                stopTimeHour = Convert.ToInt32(departureTime.Substring(0, 2));
                                hourDifferences[h] = nextStartTimeHour - stopTimeHour;
                                // Testing
                                //testingRecord.WriteLine("");
                                //testingRecord.WriteLine("CalendarStartTime: " + calendarStartTime.ToString() + " | CalendarEndTime: " + calendarEndTime.ToString() + " | Stop Time: " + departureTime + " | Stop Time Hour: " + stopTimeHour.ToString() + " | Next Start Time of Trip: " + nextStartTime.ToString() + " | Next Start Time Hour: " + nextStartTimeHour.ToString() + " | Hour Difference: " + hourDifferences[h].ToString());
                            }
                            // Create a variable for iteration
                            int sequence = 1;
                            // Grab the first hour of the stopTimes sequence
                            string firstTime;
                            if (String.IsNullOrEmpty(stopTimes[0].getProperty("departureTime").Value.ToString()))
                            {
                                firstTime = stopTimes[0].getProperty("arrivalTime").Value.ToString();
                            }
                            else
                            {
                                firstTime = stopTimes[0].getProperty("departureTime").Value.ToString();
                            }
                            int currentHour = Convert.ToInt32(firstTime.Substring(0, 2));
                            string hasBeenIncreased = "no";
                            // While the nextStartTime is less than the calendarEndTime, loop through the stopTimes and write them and a trip with every pass
                            while (nextStartTime < calendarEndTime)
                            {
                                // Write the trip
                                tripsRecord.WriteLine(trips[f].getProperty("route").Value.ToString() + "," + trips[f].getProperty("calendar").Value.ToString() + "," + tripNodeName + "_" + sequence.ToString() + "," + trips[f].getProperty("tripHeadsign").Value.ToString().Replace(",", " ") + "," + direction + ",,");
                                // Testing
                                testingRecord.WriteLine("");
                                testingRecord.WriteLine("route_id = " + trips[f].getProperty("route").Value.ToString() + "  |  service_id = " + trips[f].getProperty("calendar").Value.ToString() + "  |  trip_id = " + tripNodeName + "_" + sequence.ToString() + "  |  trip_headsign = " + trips[f].getProperty("tripHeadsign").Value.ToString().Replace(",", " ") + "  |  direction_id = " + direction + "  |  block_id =  |  shape_id = ");
                                // Loop through each of the stop times and write to the stopTimesRecord
                                for (int g = 0; g < stopTimes.Length; g++)
                                {
                                    // Send the stop time to XML
                                    XmlNode stopTimesNode = stopTimes[g].ToXml(new XmlDocument(), false);
                                    // Check to see if the stopTimesNode equals null, if so, the stop time is not published
                                    string stopTimeNodeName;
                                    if (stopTimesNode == null)
                                    {
                                        continue;
                                    }
                                    else
                                    {
                                        // Get the stop time node name from the xml node attributes
                                        stopTimeNodeName = stopTimesNode.Attributes.GetNamedItem("nodeName").Value.ToString().Replace(",", " ");
                                    }
                                    // Check to see if a stop has been selected
                                    if (stopTimes[g].getProperty("transitStop").Value.ToString() == "-1")
                                    {
                                        message.Text = message.Text + "&#8226; <span style='color: red;'>Stop Time <b>" + stopTimeNodeName + "</b> does not have a stop selected.</span><br />";
                                        errors++;
                                        continue;
                                    }
                                    // If the hourDifference is 0, then increase the currentHour
                                    //if (hourDifferences[g] == 0 && hasBeenIncreased == "no")
                                    if (g != 0)
                                    {
                                        if (hourDifferences[g] < hourDifferences[g - 1] && hasBeenIncreased == "no")
                                        {
                                            currentHour++;
                                            hasBeenIncreased = "yes";
                                        }
                                    }
                                    // Check to see if a departure time has been given, if not, set the departure time to the arrival time
                                    string arrivalTime2;
                                    string departureTime2;
                                    arrivalTime2 = currentHour.ToString() + stopTimes[g].getProperty("arrivalTime").Value.ToString().Substring(2, 6);
                                    departureTime2 = stopTimes[g].getProperty("departureTime").Value.ToString();
                                    if (String.IsNullOrEmpty(departureTime2))
                                    {
                                        departureTime2 = arrivalTime2;
                                    }
                                    else
                                    {
                                        departureTime2 = currentHour.ToString() + stopTimes[g].getProperty("departureTime").Value.ToString().Substring(2, 6);
                                    }
                                    // Testing
                                    testingRecord.WriteLine("CurrentHour: " + currentHour.ToString() + " | Has Been Increased: " + hasBeenIncreased);
                                    // Write out the stop times
                                    stopTimesRecord.WriteLine(tripNodeName + "_" + sequence.ToString() + "," + arrivalTime2 + "," + departureTime2 + "," + stopTimes[g].getProperty("transitStop").Value.ToString() + "," + (g + 1) + ",,0,0,");
                                    // Testing
                                    testingRecord.WriteLine("     stop_times.txt:  trip_id = " + tripNodeName + "_" + sequence.ToString() + "  |  arrival_time = " + arrivalTime2 + "  |  departure_time = " + departureTime2 + "  |  stop_id = " + stopTimes[g].getProperty("transitStop").Value.ToString() + "  |  stop_sequence = " + (g + 1) + "  |  stop_headsign =  |  pickup_type = 0  |  drop_off_type = 0  |  shape_dist_traveled = ");
                                }
                                // Set the new hour to be working with
                                nextStartTime = new DateTime(2011, 1, 1, currentHour, Convert.ToInt32(lastTime.Substring(3, 2)), Convert.ToInt32(lastTime.Substring(6, 2)));
                                nextStartTime = nextStartTime.AddSeconds(headway);
                                currentHour = Convert.ToInt32(nextStartTime.ToString("HH"));
                                hasBeenIncreased = "no";
                                // Testing
                                // testingRecord.WriteLine("Next Start Time: " + nextStartTime.ToString());
                                // Increase the sequence variable
                                sequence++;
                            }
                        }
                    }
                    else
                    {
                        // Check to see that the trip has a calendarStartTime and calendarEndTime
                        if (String.IsNullOrEmpty(trips[f].getProperty("calendarStartTime").Value.ToString()) || String.IsNullOrEmpty(trips[f].getProperty("calendarEndTime").Value.ToString()))
                        {
                            message.Text = message.Text + "&#8226; <span style='color: red;'>Trip <b>" + tripNodeName + "</b> is based off of another trip, but does not have a Calendar Start Time or Calendar End Time provided.</span><br />";
                            errors++;
                            continue;
                        }
                        // Check to see if the trip that this trip is based on has a tripHeadway
                        if (DBNull.Value.Equals(set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows[0]["tripHeadway"]))
                        {
                            // There is NO tripHeadway in the based on trip
                            // Write out the trip
                            tripsRecord.WriteLine(trips[f].getProperty("route").Value.ToString() + "," + trips[f].getProperty("calendar").Value.ToString() + "," + tripNodeName + "," + trips[f].getProperty("tripHeadsign").Value.ToString().Replace(",", " ") + "," + direction + ",,");
                            // Testing
                            testingRecord.WriteLine("");
                            testingRecord.WriteLine("route_id = " + trips[f].getProperty("route").Value.ToString() + "  |  service_id = " + trips[f].getProperty("calendar").Value.ToString() + "  |  trip_id = " + tripNodeName + "  |  trip_headsign = " + trips[f].getProperty("tripHeadsign").Value.ToString().Replace(",", " ") + "  |  direction_id = " + direction + "  |  block_id =  |  shape_id = ");
                            // Find out how many hours separate the calendarStartTime of the trip and the based on trip's stop times
                            int hourDifference;
                            // Loop through each of the stop times and write to the stopTimesRecord
                            for (int r = 0; r < set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows.Count; r++)
                            {
                                // Find the new arrival and departure times created by the trip's calendarStartTime
                                hourDifference = Convert.ToInt32(trips[f].getProperty("calendarStartTime").Value.ToString().Substring(0, 2)) - Convert.ToInt32(set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows[r]["arrival_time"].ToString().Substring(0, 2));
                                int newArrivalTimeHour = Convert.ToInt32(set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows[r]["arrival_time"].ToString().Substring(0, 2)) + hourDifference;
                                int newDepartureTimeHour = Convert.ToInt32(set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows[r]["departure_time"].ToString().Substring(0, 2)) + hourDifference;
                                string newArrivalTime = newArrivalTimeHour.ToString() + set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows[r]["arrival_time"].ToString().Substring(2, 6);
                                string newDepartureTime = newDepartureTimeHour.ToString() + set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows[r]["departure_time"].ToString().Substring(2, 6);
                                // Write out the stop times
                                stopTimesRecord.WriteLine(tripNodeName + "," + newArrivalTime + "," + newDepartureTime + "," + set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows[r]["stop_id"] + "," + (r + 1) + ",,0,0,");
                                // Testing
                                testingRecord.WriteLine("     stop_times.txt:  trip_id = " + tripNodeName + "  |  arrival_time = " + newArrivalTime + "  |  departure_time = " + newDepartureTime + "  |  stop_id = " + set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows[r]["stop_id"] + "  |  stop_sequence = " + (r + 1) + "  |  stop_headsign =  |  pickup_type = 0  |  drop_off_type = 0  |  shape_dist_traveled = ");
                            }
                        }
                        else
                        {
                            // There is a tripHeadway in the based on trip
                            // Create DateTime objects out of the present CalendarStartTime and CalendarEndTime
                            DateTime calendarStartTime = new DateTime(2011, 1, 1, Convert.ToInt32(trips[f].getProperty("calendarStartTime").Value.ToString().Substring(0, 2)), Convert.ToInt32(trips[f].getProperty("calendarStartTime").Value.ToString().Substring(3, 2)), Convert.ToInt32(trips[f].getProperty("calendarStartTime").Value.ToString().Substring(6, 2)));
                            DateTime calendarEndTime = new DateTime(2011, 1, 1, Convert.ToInt32(trips[f].getProperty("calendarEndTime").Value.ToString().Substring(0, 2)), Convert.ToInt32(trips[f].getProperty("calendarEndTime").Value.ToString().Substring(3, 2)), Convert.ToInt32(trips[f].getProperty("calendarEndTime").Value.ToString().Substring(6, 2)));
                            // Find out how many stops where in the based on trip
                            int stopTimesLength = set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows.Count;
                            // Find the nextStartTime of the based on trip
                            string lastTime;
                            if (String.IsNullOrEmpty(set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows[stopTimesLength - 1]["departure_time"].ToString()))
                            {
                                lastTime = set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows[stopTimesLength - 1]["arrival_time"].ToString();
                            }
                            else
                            {
                                lastTime = set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows[stopTimesLength - 1]["departure_time"].ToString();
                            }
                            DateTime lastStopTime = new DateTime(2011, 1, 1, Convert.ToInt32(lastTime.Substring(0, 2)), Convert.ToInt32(lastTime.Substring(3, 2)), Convert.ToInt32(lastTime.Substring(6, 2)));
                            // Create a double variable out of the tripHeadway of the based on trip
                            double headway = Convert.ToInt32(set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows[0]["tripHeadway"]);
                            // Add the tripHeadway to the nextStartTime to get the real nextStartTime
                            DateTime nextStartTime = lastStopTime.AddSeconds(headway);
                            // Find the hourDifferences between the nextStartTime and all of the stopTimes
                            string arrivalTime;
                            string departureTime;
                            int stopTimeHour;
                            int nextStartTimeHour = Convert.ToInt32(nextStartTime.ToString("HH"));
                            int[] hourDifferences = new int[stopTimesLength];
                            // Testing
                            // testingRecord.WriteLine("");
                            // testingRecord.WriteLine("Stop Time Information: ");
                            for (int h = 0; h < stopTimesLength; h++)
                            {
                                arrivalTime = set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows[h]["arrival_time"].ToString();
                                departureTime = set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows[h]["departure_time"].ToString();
                                // Assign the stopTimeHour
                                stopTimeHour = Convert.ToInt32(departureTime.Substring(0, 2));
                                hourDifferences[h] = nextStartTimeHour - stopTimeHour;
                                // Testing
                                // testingRecord.WriteLine("CalendarStartTime: " + calendarStartTime.ToString() + " | CalendarEndTime: " + calendarEndTime.ToString() + " | Stop Time: " + departureTime + " | Stop Time Hour: " + stopTimeHour.ToString() + " | Next Start Time of Trip: " + nextStartTime.ToString() + " | Next Start Time Hour: " + nextStartTimeHour.ToString() + " | Hour Difference: " + hourDifferences[h].ToString());
                            }
                            // Create a variable for iteration
                            int sequence = 1;
                            // Grab the first hour of the stopTimes sequence
                            string firstTime = set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows[0]["departure_time"].ToString();
                            int currentHour = Convert.ToInt32(firstTime.Substring(0, 2));
                            string hasBeenIncreased = "no";
                            // While the nextStartTime is less than the calendarEndTime, loop through the stopTimes and write them and a trip with every pass
                            while (nextStartTime < calendarEndTime)
                            {
                                // Testing
                                testingRecord.WriteLine("");
                                // Create a DateTime object for the next arrivalTime and test that it is in the calendarStartTime and calendarEndTime scope
                                DateTime arrivalTimeTest;
                                // Loop through each of the stop times and write to the stopTimesRecord
                                for (int g = 0; g < stopTimesLength; g++)
                                {
                                    // If the hourDifference is 0, then increase the currentHour
                                    if (g != 0)
                                    {
                                        if (hourDifferences[g] < hourDifferences[g - 1] && hasBeenIncreased == "no")
                                        {
                                            currentHour++;
                                            hasBeenIncreased = "yes";
                                        }
                                    }
                                    // Assign the arrivalTime2 and departureTime2 values
                                    string arrivalTime2;
                                    string departureTime2;
                                    arrivalTime2 = currentHour.ToString() + set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows[g]["arrival_time"].ToString().Substring(2, 6);
                                    departureTime2 = currentHour.ToString() + set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows[g]["departure_time"].ToString().Substring(2, 6);
                                    // Testing
                                    // testingRecord.WriteLine("CurrentHour: " + currentHour.ToString());
                                    // Set arrivalTimeTest
                                    arrivalTimeTest = new DateTime(2011, 1, 1, currentHour, Convert.ToInt32(set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows[0]["arrival_time"].ToString().Substring(3, 2)), Convert.ToInt32(set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows[0]["arrival_time"].ToString().Substring(6, 2)));
                                    if (arrivalTimeTest >= calendarStartTime && g != stopTimesLength - 1)
                                    {
                                        // Write out the stop times
                                        stopTimesRecord.WriteLine(tripNodeName + "_" + sequence.ToString() + "," + arrivalTime2 + "," + departureTime2 + "," + set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows[g]["stop_id"] + "," + (g + 1) + ",,0,0,");
                                        // Testing
                                        testingRecord.WriteLine("     stop_times.txt:  trip_id = " + tripNodeName + "_" + sequence.ToString() + "  |  arrival_time = " + arrivalTime2 + "  |  departure_time = " + departureTime2 + "  |  stop_id = " + set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows[g]["stop_id"] + "  |  stop_sequence = " + (g + 1) + "  |  stop_headsign =  |  pickup_type = 0  |  drop_off_type = 0  |  shape_dist_traveled = ");
                                    }
                                }
                                // Set arrivalTimeTest
                                arrivalTimeTest = new DateTime(2011, 1, 1, currentHour, Convert.ToInt32(set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows[0]["arrival_time"].ToString().Substring(3, 2)), Convert.ToInt32(set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows[0]["arrival_time"].ToString().Substring(6, 2)));
                                // Testing
                                testingRecord.WriteLine("Arrival Time Test: " + arrivalTimeTest);
                                // Write a variable for when a trip gets written
                                string tripWritten = "no";
                                // Only write the trip if the arrivalTimeTest is within the scope
                                if (arrivalTimeTest >= calendarStartTime)
                                {
                                    // Write the trip
                                    tripsRecord.WriteLine(trips[f].getProperty("route").Value.ToString() + "," + trips[f].getProperty("calendar").Value.ToString() + "," + tripNodeName + "_" + sequence.ToString() + "," + trips[f].getProperty("tripHeadsign").Value.ToString().Replace(",", " ") + "," + direction + ",,");
                                    // Testing
                                    testingRecord.WriteLine("route_id = " + trips[f].getProperty("route").Value.ToString() + "  |  service_id = " + trips[f].getProperty("calendar").Value.ToString() + "  |  trip_id = " + tripNodeName + "_" + sequence.ToString() + "  |  trip_headsign = " + trips[f].getProperty("tripHeadsign").Value.ToString().Replace(",", " ") + "  |  direction_id = " + direction + "  |  block_id =  |  shape_id = ");
                                    testingRecord.WriteLine("");
                                    // Set tripWritten to yes
                                    tripWritten = "yes";
                                }
                                // Set the new hour
                                nextStartTime = new DateTime(2011, 1, 1, currentHour, Convert.ToInt32(lastTime.Substring(3, 2)), Convert.ToInt32(lastTime.Substring(3, 2)));
                                nextStartTime = nextStartTime.AddSeconds(headway);
                                currentHour = Convert.ToInt32(nextStartTime.ToString("HH"));
                                hasBeenIncreased = "no";
                                // Testing
                                // testingRecord.WriteLine("Next Start Time: " + nextStartTime.ToString());
                                // Increase the sequence variable
                                if (tripWritten == "yes")
                                {
                                    sequence++;
                                }
                            }
                        }
                        //testingRecord.WriteLine("");
                        //testingRecord.WriteLine("Table Name: " + set.Tables[tripNodeName] + " | Table that it is based on = " + trips[f].getProperty("tripBasedOn").Value.ToString() + " | Based on Tables's Row Count: = " + set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows.Count + " | Based on tables's tripHeadway = " + set.Tables[trips[f].getProperty("tripBasedOn").Value.ToString()].Rows[0]["tripHeadway"]);
                        //testingRecord.WriteLine("");
                    }
                }
                // Testing
                testingRecord.WriteLine("");

                // Get the fare_attributes.txt information from the Transit Fares children nodes and write it to fareAttributesRecord
                Document[] fares = new Document(faresRoot).Children;
                // Testing
                testingRecord.WriteLine("fare_attributes.txt");
                for (int h = 0; h < fares.Length; h++)
                {
                    // Send the fare to XML
                    XmlNode faresNode = fares[h].ToXml(new XmlDocument(), false);
                    // Check to see if the faresNode equals null, if so, the fare is not published
                    string fareNodeName;
                    if (faresNode == null)
                    {
                        continue;
                    }
                    else
                    {
                        // Get the route node name from the xml node attributes
                        fareNodeName = faresNode.Attributes.GetNamedItem("nodeName").Value.ToString();
                    }
                    // Set the transfer option to a value - 0 = No transfers allowed, 1 = 1 transfer allowed, 2 = 2 transfers allowed and empty = Unlimited transfers allowed
                    string transfers;
                    if (fares[h].getProperty("fareTransfers").Value.ToString() == "135")
                    {
                        transfers = "0";
                    }
                    else if (fares[h].getProperty("fareTransfers").Value.ToString() == "136")
                    {
                        transfers = "1";
                    }
                    else if (fares[h].getProperty("fareTransfers").Value.ToString() == "137")
                    {
                        transfers = "2";
                    }
                    else
                    {
                        transfers = "";
                    }
                    // Check to see if a transfer duration has been provided if a transfer is available, if not, return an error
                    if ((transfers == "1" || transfers == "2" || transfers == "") && String.IsNullOrEmpty(fares[h].getProperty("fareTransferDuration").Value.ToString()))
                    {
                        message.Text = message.Text + "&#8226; <span style='color: red;'>Fare <b>" + fareNodeName + "</b> has transfers allowed, but does not have a transfer duration provided.</span><br />";
                        errors++;
                        continue;
                    }
                    // Write the fare attribute information
                    fareAttributesRecord.WriteLine(fareNodeName + "," + fares[h].getProperty("farePrice").Value.ToString() + ",USD,0," + transfers + "," + fares[h].getProperty("fareTransferDuration").Value.ToString());
                    // Testing
                    testingRecord.WriteLine("");
                    testingRecord.WriteLine("fare_id = " + fareNodeName + "  |  price = " + fares[h].getProperty("farePrice").Value.ToString() + "  |  currency_type = USD  |  payment_method = 0  |  transfers = " + transfers + "  |  transfer_duration = " + fares[h].getProperty("fareTransferDuration").Value.ToString());
                    // Check to see if they are using the Routes or Origin and Destination Zones, if they are not using one or the other, return an error
                    if (String.IsNullOrEmpty(fares[h].getProperty("fareRoutes").Value.ToString()) && fares[h].getProperty("fareOriginZone").Value.ToString() == "-1" && fares[h].getProperty("fareDestinationZone").Value.ToString() == "-1")
                    {
                        message.Text = message.Text + "&#8226; <span style='color: red;'>Fare <b>" + fareNodeName + "</b> does not have any Routes selected or does not have an Origin Zone and Destination Zone selected.</span><br />";
                        errors++;
                        continue;
                    }
                    // Check to see if they are using Routes and not Origin and Destination Zones
                    if (!String.IsNullOrEmpty(fares[h].getProperty("fareRoutes").Value.ToString()) && fares[h].getProperty("fareOriginZone").Value.ToString() == "-1" && fares[h].getProperty("fareDestinationZone").Value.ToString() == "-1")
                    {
                        // Take the csv fareRoutes string and separate it by comma
                        string[] fareRoutes = fares[h].getProperty("fareRoutes").Value.ToString().Split(',');
                        // Loop through the fareRoutes string and add a new fare rule to the fareRulesRecord for each
                        for (int g = 0; g < fareRoutes.Length; g++)
                        {
                            // Write the fare rules information
                            fareRulesRecord.WriteLine(fareNodeName + "," + fareRoutes[g] + ",,,");
                            // Testing
                            testingRecord.WriteLine("     fare_rules.txt:  fare_id = " + fareNodeName + "  |  route_id = " + fareRoutes[g] + "  |  origin_id =  |  destination_id =  | contains_id = ");
                        }
                    }
                    // Check to see if they are using Origin and Destination Zones, these options will override the Routes
                    if ((!String.IsNullOrEmpty(fares[h].getProperty("fareRoutes").Value.ToString()) || String.IsNullOrEmpty(fares[h].getProperty("fareRoutes").Value.ToString())) && (fares[h].getProperty("fareOriginZone").Value.ToString() != "-1" || fares[h].getProperty("fareDestinationZone").Value.ToString() != "-1"))
                    {
                        // Check to see that both the Origin Zone and Destination Zone have been selected, if they haven't, return an error
                        if (fares[h].getProperty("fareOriginZone").Value.ToString() == "-1" && fares[h].getProperty("fareDestinationZone").Value.ToString() == "-1")
                        {
                            message.Text = message.Text + "&#8226; <span style='color: red;'>Fare <b>" + fareNodeName + "</b> has a Origin Zone selected or a Destination Zone selected but not both. Both must be selected if that is the option chosen.</span><br />";
                            errors++;
                            continue;
                        }
                        // Write the fare rules information with the Origin and Destination Zone options
                        fareRulesRecord.WriteLine(fareNodeName + ",," + fares[h].getProperty("fareOriginZone").Value.ToString() + "," + fares[h].getProperty("fareDestinationZone").Value.ToString() + ",");
                        // Testing
                        testingRecord.WriteLine("     fare_rules.txt:  fare_id = " + fareNodeName + "  |  route_id =  |  origin_id = " + fares[h].getProperty("fareOriginZone").Value.ToString() + "  |  destination_zone = " + fares[h].getProperty("fareDestinationZone").Value.ToString() + "  |  contains_id = ");
                    }
                }
                // Testing
                testingRecord.WriteLine("");

                // Close and Dispose of all Records and run GC.Collect()
                agencyRecord.Close();
                feedInfoRecord.Close();
                routesRecord.Close();
                stopsRecord.Close();
                calendarsRecord.Close();
                calendarDatesRecord.Close();
                tripsRecord.Close();
                stopTimesRecord.Close();
                fareAttributesRecord.Close();
                fareRulesRecord.Close();
                testingRecord.Close();

                agencyRecord.Dispose();
                feedInfoRecord.Dispose();
                routesRecord.Dispose();
                stopsRecord.Dispose();
                calendarsRecord.Dispose();
                calendarDatesRecord.Dispose();
                tripsRecord.Dispose();
                stopTimesRecord.Dispose();
                fareAttributesRecord.Dispose();
                fareRulesRecord.Dispose();
                testingRecord.Dispose();

                GC.Collect();
            }
            catch (IOException except)
            {
                status.Text = except.Message;
            }

            // If there are no errors, zip up the files and validate the feed
            if (errors > 0)
            {
                status.Text = "<b>Feed NOT Published.</b> Last attempted -- " + DateTime.Now.ToString("dddd, MMMM dd, yyyy hh:mm tt");
                if (errors == 1)
                {
                    message.Text = message.Text + "<br /><b>There is currently " + errors + " error in your transit grouping.</b><br /><br />The Feed Creation has been halted until this error can be resolved.";
                }
                else
                {
                    message.Text = message.Text + "<br /><b>There are currently " + errors + " errors in your transit grouping.</b><br /><br />The Feed Creation has been halted until these errors can be resolved.";
                }
            }
            else
            {
                // Zip up the txt files
                if (!File.Exists(transitDirectory + "\\" + arch))
                {
                    ZipFile output = new ZipFile();
                    output.AddFile(transitDirectory + "\\agency.txt", ".");
                    output.AddFile(transitDirectory + "\\feed_info.txt", ".");
                    output.AddFile(transitDirectory + "\\routes.txt", ".");
                    output.AddFile(transitDirectory + "\\stops.txt", ".");
                    output.AddFile(transitDirectory + "\\calendar.txt", ".");
                    output.AddFile(transitDirectory + "\\calendar_dates.txt", ".");
                    output.AddFile(transitDirectory + "\\trips.txt", ".");
                    output.AddFile(transitDirectory + "\\stop_times.txt", ".");
                    output.AddFile(transitDirectory + "\\fare_attributes.txt", ".");
                    output.AddFile(transitDirectory + "\\fare_rules.txt", ".");
                    output.Name = transitDirectory + "\\" + arch;
                    output.Save();
                    output.Dispose();
                    GC.Collect();
                }
                else
                {
                    ZipFile output = new ZipFile(transitDirectory + "\\" + arch);
                    output.UpdateFile(transitDirectory + "\\agency.txt", ".");
                    output.UpdateFile(transitDirectory + "\\feed_info.txt", ".");
                    output.UpdateFile(transitDirectory + "\\routes.txt", ".");
                    output.UpdateFile(transitDirectory + "\\stops.txt", ".");
                    output.UpdateFile(transitDirectory + "\\calendar.txt", ".");
                    output.UpdateFile(transitDirectory + "\\calendar_dates.txt", ".");
                    output.UpdateFile(transitDirectory + "\\trips.txt", ".");
                    output.UpdateFile(transitDirectory + "\\stop_times.txt", ".");
                    output.UpdateFile(transitDirectory + "\\fare_attributes.txt", ".");
                    output.UpdateFile(transitDirectory + "\\fare_rules.txt", ".");
                    output.Save();
                    output.Dispose();
                    GC.Collect();
                }

                // Feed validation
                try
                {
                    string fileName = transitDirectory + @"\\feedvalidator_googletransit.exe";
                    Process cmdLineProcess = new Process();
                    cmdLineProcess.StartInfo.FileName = fileName;
                    cmdLineProcess.StartInfo.Arguments = "-o " + transitDirectory + "\\error.html -l 9999 " + transitDirectory + "\\" + arch;
                    cmdLineProcess.StartInfo.UseShellExecute = true;
                    cmdLineProcess.StartInfo.CreateNoWindow = true;
                    cmdLineProcess.StartInfo.RedirectStandardOutput = false;
                    cmdLineProcess.StartInfo.RedirectStandardError = false;
                    if (cmdLineProcess.Start())
                    {
                        //litsample1.Text = cmdLineProcess.StandardOutput.ReadToEnd();
                    }
                    else
                    {
                        throw new ApplicationException("Can't read the command line process:" + fileName);
                    }
                }
                catch (ApplicationException except)
                {
                    message.Text = message.Text + except.Message;
                }

                status.Text = "<b>Feed Published Successfully</b> -- " + DateTime.Now.ToString("dddd, MMMM dd, yyyy hh:mm tt");
                message.Text = message.Text + "<br />View the full Feed Validation Report: <a href='/transit/error.html' target='_blank'>Google Feed Validation Report</a><br />View the testing.txt file: <a href='/transit/testing.txt' target='_blank'>testing.txt</a>";
            }

            return;
        }
Example #34
0
        public XmlRpcResponse XmlRpcHandler(XmlRpcRequest request, IPEndPoint client)
        {
            // AuthClient.VerifySession(GetUserServerURL(userID), userID, sessionID);
            m_log.Info("[SCENEUPLOADER] Loading Scenex");
            XmlRpcResponse response    = new XmlRpcResponse();
            Hashtable      requestData = (Hashtable)request.Params[0];
            Hashtable      resp        = new Hashtable();

            resp["success"] = false;
            resp["error"]   = String.Empty;
            m_log.Info("[SCENEUPLOADER] Parsing Request");

            if (requestData.ContainsKey("AgentID") &&
                requestData.ContainsKey("AvatarURL") &&
                requestData.ContainsKey("RegionID") &&
                requestData.ContainsKey("PackName"))
            {
                UUID agentID;
                UUID regionID = UUID.Parse((string)requestData["RegionID"]);
                m_scene = SelectRegion(regionID);
                string avatarUrl;
                string packName = (string)requestData["PackName"];
                m_log.Info("[SCENEUPLOADER] Write zip file to disk ");
                FileStream fout = new FileStream("/tmp/test.zip", FileMode.Create);
                byte[]     data = (byte[])requestData["AvatarURL"];
                fout.Write(data, 0, data.Length);
                fout.Close();

                Ionic.Zip.ZipFile f = null;
                try
                {
                    f = Ionic.Zip.ZipFile.Read("/tmp/test.zip");
                    f.ExtractAll("/tmp/foo");
                    f.Dispose();
                }
                catch (Exception)
                {
                    if (f != null)
                    {
                        f.Dispose();
                    }
                    throw;
                }


                OgreSceneImportModule osi = (OgreSceneImportModule)m_scene.Modules["OgreSceneImportModule"];
                try
                {
                    osi.ImportUploadedOgreScene("/tmp/foo/" + packName, m_scene);
                }
                catch (Exception)
                {
                    m_log.Error("[SCENEUPLOADER] Error importing uploaded scene " + packName);
                    Directory.Delete("/tmp/foo", true);
                    File.Delete("/tmp/test.zip");
                    throw;
                }

                m_log.Info("[SCENEUPLOADER] Cleaning up");
                Directory.Delete("/tmp/foo", true);
                File.Delete("/tmp/test.zip");

                resp["success"] = true;
            }

            response.Value = resp;
            m_log.Info("[SCENEUPLOADER] Scene Loaded" + requestData["PackName"].ToString());
            return(response);
        }
Example #35
0
		public static string SaveAllConfigToFile(bool saveAnyway = false)
		{
			try
			{
				var tempFolderName = AppDataFolderHelper.GetTempFolder();
				if (!Directory.Exists(tempFolderName))
					Directory.CreateDirectory(tempFolderName);

				var tempFileName = AppDataFolderHelper.GetTempFileName();
				if (File.Exists(tempFileName))
					File.Delete(tempFileName);

				TempZipConfigurationItemsCollection = new ZipConfigurationItemsCollection();

				if (ServiceFactory.SaveService.FSChanged || ServiceFactory.SaveService.FSParametersChanged || saveAnyway)
					AddConfiguration(tempFolderName, "DeviceConfiguration.xml", FiresecManager.FiresecConfiguration.DeviceConfiguration, 1, 1);
				if (ServiceFactory.SaveService.PlansChanged || saveAnyway)
					AddConfiguration(tempFolderName, "PlansConfiguration.xml", FiresecManager.PlansConfiguration, 1, 1);
				if ((ServiceFactory.SaveService.InstructionsChanged) || (ServiceFactory.SaveService.SoundsChanged) || (ServiceFactory.SaveService.FilterChanged) || (ServiceFactory.SaveService.CamerasChanged) || (ServiceFactory.SaveService.EmailsChanged) || saveAnyway)
					AddConfiguration(tempFolderName, "SystemConfiguration.xml", FiresecManager.SystemConfiguration, 1, 1);
				if (ServiceFactory.SaveService.GKChanged || ServiceFactory.SaveService.XInstructionsChanged || saveAnyway)
					AddConfiguration(tempFolderName, "XDeviceConfiguration.xml", XManager.DeviceConfiguration, 1, 1);
				AddConfiguration(tempFolderName, "ZipConfigurationItemsCollection.xml", TempZipConfigurationItemsCollection, 1, 1);
				if (ServiceFactory.SaveService.SecurityChanged || saveAnyway)
					AddConfiguration(tempFolderName, "SecurityConfiguration.xml", FiresecManager.SecurityConfiguration, 1, 1);
				if (ServiceFactory.SaveService.LibraryChanged || saveAnyway)
					AddConfiguration(tempFolderName, "DeviceLibraryConfiguration.xml", FiresecManager.DeviceLibraryConfiguration, 1, 1);
				if (ServiceFactory.SaveService.XLibraryChanged || saveAnyway)
					AddConfiguration(tempFolderName, "XDeviceLibraryConfiguration.xml", XManager.DeviceLibraryConfiguration, 1, 1);
				if (ServiceFactory.SaveService.SKDChanged || saveAnyway)
					AddConfiguration(tempFolderName, "SKDConfiguration.xml", SKDManager.SKDConfiguration, 1, 1);
				if (ServiceFactory.SaveService.SKDLibraryChanged || saveAnyway)
					AddConfiguration(tempFolderName, "SKDLibraryConfiguration.xml", SKDManager.SKDLibraryConfiguration, 1, 1);
				if (ServiceFactory.SaveService.LayoutsChanged || saveAnyway)
					AddConfiguration(tempFolderName, "LayoutsConfiguration.xml", FiresecManager.LayoutsConfiguration, 1, 1);

				var destinationImagesDirectory = AppDataFolderHelper.GetFolder(Path.Combine(tempFolderName, "Content"));
				if (Directory.Exists(ServiceFactory.ContentService.ContentFolder))
				{
					if (Directory.Exists(destinationImagesDirectory))
						Directory.Delete(destinationImagesDirectory);
					if (!Directory.Exists(destinationImagesDirectory))
						Directory.CreateDirectory(destinationImagesDirectory);
					var sourceImagesDirectoryInfo = new DirectoryInfo(ServiceFactory.ContentService.ContentFolder);
					foreach (var fileInfo in sourceImagesDirectoryInfo.GetFiles())
					{
						fileInfo.CopyTo(Path.Combine(destinationImagesDirectory, fileInfo.Name));
					}
				}

				var zipFile = new ZipFile(tempFileName);
				zipFile.AddDirectory(tempFolderName);
				zipFile.Save(tempFileName);
				zipFile.Dispose();
				if (Directory.Exists(tempFolderName))
					Directory.Delete(tempFolderName, true);

				return tempFileName;
			}
			catch (Exception e)
			{
				Logger.Error(e, "ConfigManager.SaveAllConfigToFile");
			}
			return null;
		}
Example #36
0
 void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
 {
     str_m += "download end and extract mongodb zip\n";
     ZipFile zip = new ZipFile(address2);
     zip.ExtractProgress += zip_ExtractProgress;
     zip.ExtractAll(AppDomain.CurrentDomain.BaseDirectory, ExtractExistingFileAction.OverwriteSilently);
     zip.Dispose();
     info.mongo_address = AppDomain.CurrentDomain.BaseDirectory + "/" + file_name + "/bin";
     str_m += "extracte end and mongodb setting finish\n";
 }
Example #37
0
        void AsyncWorker()
        {
            Dispatcher.Invoke(new MyDelegate(() =>
            {
                updateLabel.Content = "Подключение к серверу...";
            }));
            gameInfo   = new GameInfo();
            updateInfo = new UpdateInfo(gameInfo);
            updateInfo.State.WaitOne();
            bool terminate = false;

            Dispatcher.Invoke(new MyDelegate(() =>
            {
                if (updateInfo.FileSize != 0 && MessageBox.Show("Доступен новый патч, установить?\n " + updateInfo.ChangLog, "Recoding Updater", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    updateLabel.Content = String.Format("Скачивание патча. Размер: {0} KB", updateInfo.FileSize / 1024);
                }
                else
                {
                    Process.Start(gameInfo.GameExe);
                    Close();
                    terminate = true;
                }
            }));

            if (terminate)
            {
                return;
            }
            Dispatcher.Invoke(new MyDelegate(() =>
            {
                progressBar.Maximum = updateInfo.FileSize;
            }));

            Stream     reader = Extensions.GetFtpResponse(updateInfo.PatchFile, gameInfo.Credentials, WebRequestMethods.Ftp.DownloadFile).GetResponseStream();
            FileStream fs     = new FileStream("patch.zip", FileMode.Create);

            byte[] buffer = new byte[512 * 1024];

            long time = DateTime.Now.Ticks;

            while (true)
            {
                int bytesRead = reader.Read(buffer, 0, buffer.Length);

                if (bytesRead == 0)
                {
                    fs.Flush();
                    fs.Close();
                    break;
                }
                else
                {
                    long dt = DateTime.Now.Ticks - time;
                    fs.Write(buffer, 0, bytesRead);
                    Dispatcher.Invoke(new MyDelegate(() =>
                    {
                        progressBar.Value  += bytesRead;
                        float vel           = (float)progressBar.Value / dt * 10000000 / 1024;
                        updateLabel.Content = String.Format("Скачивание патча @ {2} КБ / c. Размер: {0} / {1} KB", (int)progressBar.Value / 1024, updateInfo.FileSize / 1024, (int)vel);
                    }));
                }
            }

            Dispatcher.Invoke(new MyDelegate(() =>
            {
                progressBar.Value   = 0;
                updateLabel.Content = String.Format("Распаковка патча. Размер: {0} KB", updateInfo.FileSize / 1024);
            }));

            Zip.ZipFile zf = new Zip.ZipFile("patch.zip");
            zf.ExtractProgress += new EventHandler <Zip.ExtractProgressEventArgs>(zf_ExtractProgress);
            string dir;

            if (updateInfo.Type == UpdateType.Regular)
            {
                dir = Directory.GetCurrentDirectory();
            }
            else
            {
                dir = Directory.GetCurrentDirectory() + "\\~tmp";
            }

            zf.ExtractAll(dir, Zip.ExtractExistingFileAction.OverwriteSilently);
            zf.Dispose();

            File.Delete("patch.zip");

            Dispatcher.Invoke(new MyDelegate(() =>
            {
                updateLabel.Content = String.Format("Ожидание завершения...");
            }));

            string msg;

            if (updateInfo.Type == UpdateType.Regular)
            {
                msg = "Патч установлен. Запустить программу?";
            }
            else
            {
                msg = "Патч скачан. Запустить его установку?";
            }

            MessageBoxResult res = MessageBoxResult.Yes;


            Dispatcher.Invoke(new MyDelegate(() =>
            {
                res = MessageBox.Show(msg, "Recoding Updater", MessageBoxButton.YesNo);
            }));


            if (updateInfo.Type == UpdateType.Regular)
            {
                StreamWriter sw = new StreamWriter(new FileStream("version.txt", FileMode.Create));
                sw.Write(updateInfo.LastPatch);
                sw.Flush();
                sw.Close();
            }


            if (res == MessageBoxResult.Yes)
            {
                if (updateInfo.Type == UpdateType.Regular)
                {
                    Process.Start(gameInfo.GameExe);
                }
                else
                {
                    Process p = new Process();
                    p.StartInfo = new ProcessStartInfo("~tmp\\" + gameInfo.SetupExe);
                    p.Start();
                    p.WaitForExit();

                    if (p.ExitCode == 0)
                    {
                        StreamWriter sw = new StreamWriter(new FileStream("version.txt", FileMode.Create));
                        sw.Write(updateInfo.LastPatch);
                        sw.Flush();
                        sw.Close();
                        Directory.Delete("~tmp", true);
                    }
                    else
                    {
                        Dispatcher.Invoke(new MyDelegate(() =>
                        {
                            MessageBox.Show("Установка патча не удалась. Возможно ваш антивирус блокирует установку. В любом случае попробуйте установить патч вручную из каталога ~tmp.");
                        }));
                    }
                }
            }

            Dispatcher.Invoke(new MyDelegate(() =>
            {
                Close();
            }));
        }
Example #38
0
        /// <summary>
        /// Exports data to a KMZ file.
        /// </summary>
        /// <param name="tempBasePath">A temporary path where files creatred during the export will reside. This path should not exist before calling this method. The path is deleted when this method completes.</param>
        public void ExportKmz(string tempBasePath)
        {
            LogUtil.LogDebug("Started");
              // 1. create temp directories and the kmz file
              temporaryBasePath = tempBasePath;
              Directory.CreateDirectory(temporaryBasePath);
              Directory.CreateDirectory(temporaryBasePath + @"files\");
              kmzFile = new ZipFile();
              kmzFile.AddDirectoryByName("files");

              // 2. create ground overlay image streams for each document
              LogUtil.LogDebug("Creating overlays");
              var groundOverlayCount = 0;
              GroundOverlays = new Dictionary<KmlExportDocument, KmlGroundOverlay>();
              foreach (var document in kmlExportDocuments)
              {
            if (KmlProperties.MapType != KmlExportMapType.None)
            {
              var fileName = temporaryBasePath + @"files\o" + groundOverlayCount + "." + document.ImageExporter.Properties.EncodingInfo.Encoder.MimeType.Replace("image/", ""); // NOTE: this assumes that the mime type matches the file extension
              using (var imageStream = new FileStream(fileName, FileMode.Create))
              {
            document.ImageExporter.OutputStream = imageStream;
            switch (KmlProperties.MapType)
            {
              case KmlExportMapType.Map:
                document.ImageExporter.Properties.RouteDrawingMode = Document.RouteDrawingMode.None;
                break;
              case KmlExportMapType.MapAndRoute:
                document.ImageExporter.Properties.RouteDrawingMode = Document.RouteDrawingMode.Extended;
                break;
            }
            document.ImageExporter.Export();

            GroundOverlays.Add(document, new KmlGroundOverlay(fileName, KmlGroundOverlay.GroundOverlayType.File));
            groundOverlayCount++;
              }
            }
              }

              // 3. generate kml document
              LogUtil.LogDebug("Generating kml document");
              var tempKmlFileName = temporaryBasePath + "doc.kml";
              using (var kmlStream = new FileStream(tempKmlFileName, FileMode.Create))
              {
            var writerSettings = new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true, IndentChars = "  " };
            using (var writer = XmlWriter.Create(kmlStream, writerSettings))
            {
              CreateKml(writer);
              writer.Close();
              kmzFile.AddFile(tempKmlFileName, "");
            }
              }
              kmzFile.Save(OutputStream);
              kmzFile.Dispose();

              // 4. delete temp directory and its content
              LogUtil.LogDebug("Deleting temp dir");
              Directory.Delete(temporaryBasePath, true);
              LogUtil.LogDebug("Finished");
        }
Example #39
0
        public void UninstallAddon(AddonMetaData addon)
        {
            MainView.StatusMessage = string.Format("Uninstalling Addon {0}", addon.Name);

            // Addon, nice and easy
            if (addon.IsAddon)
            {
                // Remove all the installed files
                foreach (string filePath in addon.InstalledFilesList)
                {
                    string path = filePath;

                    if (path.StartsWith("Addons/")) // Melder added "Addons/" to the start when an addon was put under the my docs location so remove it
                        path = filePath.Replace("Addons/", "");

                    path = Statics.FixPathSlashes(Path.Combine(Statics.AddonsFolder, filePath));
                    if (File.Exists(path) && Statics.IsPathSafe(path))
                    {
                        File.Delete(path);
                    }
                    else if (Directory.Exists(path) && Statics.IsPathSafe(path) && Directory.GetFiles(path).Length == 0)
                    {
                        Directory.Delete(path, true);
                    }
                }

                // The info File
                string infoPath = Path.Combine(Statics.AddonsFolder, "melder_addons", Path.GetFileName(addon.ZipName)+".ini");
                if (File.Exists(infoPath) && Statics.IsPathSafe(infoPath))
                {
                    File.Delete(infoPath);
                }
            }
            else // Mods, remove and then restore backups
            {
                foreach (string filePath in addon.InstalledFilesList)
                {
                    string modFilePath = Statics.FixPathSlashes(Path.Combine(MeldiiSettings.Self.FirefallInstallPath, "system", filePath));
                    if (File.Exists(modFilePath) && Statics.IsPathSafe(modFilePath))
                    {
                        Debug.WriteLine("Uninstall, Deleting file: " + modFilePath);
                        File.Delete(modFilePath);
                    }
                    else if (Directory.Exists(modFilePath) && Statics.IsPathSafe(modFilePath) && Directory.GetFiles(modFilePath).Length == 0) // Make sure it is empty
                    {

                    }
                }

                // Restore the backup
                string backUpFilePath = Statics.GetBackupPathForMod(Path.GetFileNameWithoutExtension(addon.ZipName));

                if (File.Exists(backUpFilePath))
                {
                    ZipFile backUp = new ZipFile(backUpFilePath);
                    backUp.ExtractAll(Path.Combine(MeldiiSettings.Self.FirefallInstallPath, "system"), ExtractExistingFileAction.DoNotOverwrite);
                    backUp.Dispose();
                }

                // The info File
                string infoPath = Path.Combine(Path.Combine(MeldiiSettings.Self.FirefallInstallPath, Statics.ModDataStoreReltivePath), Path.GetFileName(addon.ZipName) + ".ini");
                if (File.Exists(infoPath) && Statics.IsPathSafe(infoPath))
                {
                    File.Delete(infoPath);
                }
            }

            MainView.StatusMessage = string.Format("Addon {0} Uninstalled", addon.Name);
        }
        public List<Common.Tuple<String, System.Action>> GetLoadSteps(string filename, SlimDX.Direct3D9.Device device, out Map outMap)
        {
            var baseFileName = Path.GetFileName(filename);
            var map = new Map { MapName = baseFileName, MapFileName = Path.GetFullPath(filename) };
            outMap = map;
            var mapFile = new ZipFile(filename);
            map.OnResetDevice = () => OnResetDevice(map);

            var a = new List<Common.Tuple<string, System.Action>>();

            a.Add(new Common.Tuple<string, System.Action>("Loading settings",
                () => map.Settings = LoadSettings(baseFileName, mapFile)));

            a.Add(new Common.Tuple<string, System.Action>("Loading static data", () => LoadStaticData(map, mapFile)));
            a.Add(new Common.Tuple<string, System.Action>("Loading dynamic data", () => LoadDynamicData(map, mapFile)));
            a.Add(new Common.Tuple<string, System.Action>("Loading language data",
                () => map.StringLocalizationStorage = LoadLanguageData(baseFileName, mapFile)));

            a.Add(new Common.Tuple<string, System.Action>("NormalizeStaticDynamicObjects",
                map.NormalizeStaticDynamicObjects));

            a.Add(new Common.Tuple<string, System.Action>("Init scene root", () =>
            {

                foreach (var v in map.DynamicsRoot.Offspring)
                    if (v is GameEntity)
                        ((GameEntity)v).Map = map;

                foreach (var v in map.StaticsRoot.Offspring)
                    if (v is GameEntity)
                        ((GameEntity)v).Map = map;

                map.FindMainCharacter();
            }));

            a.Add(new Common.Tuple<string, System.Action>("Creating ground", () =>
            {
                map.Ground = new Ground();
                map.InitGround();
            }));

            a.Add(new Common.Tuple<string, System.Action>("Loading SplatMap", () => LoadSplatMap(map, device, mapFile)));

            a.Add(new Common.Tuple<string, System.Action>("Loading SplatMap2", () => LoadSplatMap2(map, device, mapFile)));

            a.Add(new Common.Tuple<string, System.Action>("Loading Heightmap", () => LoadHeightmap(map, mapFile)));
            a.Add(new Common.Tuple<string, System.Action>("Constructing ground pieces", () => map.Ground.ConstructPieces(map)));

            a.Add(new Common.Tuple<string, System.Action>("Initializing ground", () =>
            {
                if (map.Ground.SplatMap1 != null && map.Ground.SplatMap2 != null)
                    map.Ground.Init();
            }));

            a.Add(new Common.Tuple<string, System.Action>("Done", () =>
            {
                mapFile.Dispose();
            }));

            return a;
        }
        /// <summary>
        ///   Checks a zip file to see if its directory is consistent,
        ///   and optionally fixes the directory if necessary.
        /// </summary>
        ///
        /// <remarks>
        ///
        /// <para>
        ///   In cases of data error, the directory within a zip file can get out of
        ///   synch with the entries in the zip file.  This method checks the given
        ///   zip file, and returns true if this has occurred. It also optionally
        ///   fixes the zipfile, saving the fixed copy in <em>Name</em>_Fixed.zip.
        /// </para>
        ///
        /// <para>
        ///   This method may take a long time to run for large zip files.  It
        ///   will take even longer if the file actually needs to be fixed, and if
        ///   <c>fixIfNecessary</c> is true.
        /// </para>
        ///
        /// <para>
        ///   This method is not supported in the Reduced or Compact
        ///   Framework versions of DotNetZip.
        /// </para>
        ///
        /// </remarks>
        ///
        /// <param name="zipFileName">The filename to of the zip file to check.</param>
        ///
        /// <param name="fixIfNecessary">If true, the method will fix the zip file if
        ///     necessary.</param>
        ///
        /// <param name="writer">
        /// a TextWriter in which messages generated while checking will be written.
        /// </param>
        ///
        /// <returns>true if the named zip is OK; false if the file needs to be fixed.</returns>
        ///
        /// <seealso cref="CheckZip(string)"/>
        /// <seealso cref="FixZipDirectory(string)"/>
        public static bool CheckZip(string zipFileName, bool fixIfNecessary,
                                    TextWriter writer)

        {
            ZipFile zip1 = null, zip2 = null;
            bool    isOk = true;

            try
            {
                zip1          = new ZipFile();
                zip1.FullScan = true;
                zip1.Initialize(zipFileName);

                zip2 = ZipFile.Read(zipFileName);

                foreach (var e1 in zip1)
                {
                    foreach (var e2 in zip2)
                    {
                        if (e1.FileName == e2.FileName)
                        {
                            if (e1._RelativeOffsetOfLocalHeader != e2._RelativeOffsetOfLocalHeader)
                            {
                                isOk = false;
                                if (writer != null)
                                {
                                    writer.WriteLine("{0}: mismatch in RelativeOffsetOfLocalHeader  (0x{1:X16} != 0x{2:X16})",
                                                     e1.FileName, e1._RelativeOffsetOfLocalHeader,
                                                     e2._RelativeOffsetOfLocalHeader);
                                }
                            }
                            if (e1._CompressedSize != e2._CompressedSize)
                            {
                                isOk = false;
                                if (writer != null)
                                {
                                    writer.WriteLine("{0}: mismatch in CompressedSize  (0x{1:X16} != 0x{2:X16})",
                                                     e1.FileName, e1._CompressedSize,
                                                     e2._CompressedSize);
                                }
                            }
                            if (e1._UncompressedSize != e2._UncompressedSize)
                            {
                                isOk = false;
                                if (writer != null)
                                {
                                    writer.WriteLine("{0}: mismatch in UncompressedSize  (0x{1:X16} != 0x{2:X16})",
                                                     e1.FileName, e1._UncompressedSize,
                                                     e2._UncompressedSize);
                                }
                            }
                            if (e1.CompressionMethod != e2.CompressionMethod)
                            {
                                isOk = false;
                                if (writer != null)
                                {
                                    writer.WriteLine("{0}: mismatch in CompressionMethod  (0x{1:X4} != 0x{2:X4})",
                                                     e1.FileName, e1.CompressionMethod,
                                                     e2.CompressionMethod);
                                }
                            }
                            if (e1.Crc != e2.Crc)
                            {
                                isOk = false;
                                if (writer != null)
                                {
                                    writer.WriteLine("{0}: mismatch in Crc32  (0x{1:X4} != 0x{2:X4})",
                                                     e1.FileName, e1.Crc,
                                                     e2.Crc);
                                }
                            }

                            // found a match, so stop the inside loop
                            break;
                        }
                    }
                }

                zip2.Dispose();
                zip2 = null;

                if (!isOk && fixIfNecessary)
                {
                    string newFileName = Path.GetFileNameWithoutExtension(zipFileName);
                    newFileName = System.String.Format("{0}_fixed.zip", newFileName);
                    zip1.Save(newFileName);
                }
            }
            finally
            {
                if (zip1 != null)
                {
                    zip1.Dispose();
                }
                if (zip2 != null)
                {
                    zip2.Dispose();
                }
            }
            return(isOk);
        }
Example #42
0
        /// <summary>
        /// Checks a zip file to see if its directory is consistent,
        /// and optionally fixes the directory if necessary.
        /// </summary>
        ///
        /// <remarks>
        ///
        /// <para> In cases of data error, the directory within a zip file can get out of
        ///     synch with the entries in the zip file.  This method checks the given
        ///     zip file, and returns true if this has occurred. It also optionally
        ///     fixes the zipfile, saving the fixed copy in <em>Name</em>_Fixed.zip.</para>
        ///
        /// <para> This method may take a long time to run for large zip files.  It will
        ///     take even longer if the file actually needs to be fixed, and if
        ///     <c>fixIfNecessary</c> is true.  </para>
        ///
        /// <para>
        /// This method is not supported in the Reduced or Compact
        /// Framework versions of DotNetZip.
        /// </para>
        ///
        /// </remarks>
        ///
        /// <param name="zipFileName">The filename to of the zip file to check.</param>
        ///
        /// <param name="fixIfNecessary">If true, the method will fix the zip file if
        ///     necessary.</param>
        ///
        /// <param name="messages">
        /// a collection of messages generated while checking, indicating any problems that are found.
        /// </param>
        ///
        /// <returns>true if the named zip is OK; false if the file needs to be fixed.</returns>
        ///
        /// <seealso cref="CheckZip(string)"/>
        /// <seealso cref="FixZipDirectory(string)"/>
        public static bool CheckZip(string zipFileName, bool fixIfNecessary,
                                    out System.Collections.ObjectModel.ReadOnlyCollection <String> messages)
        {
            List <String> notes = new List <String>();
            ZipFile       zip1  = null;
            ZipFile       zip2  = null;
            bool          isOk  = true;

            try
            {
                zip1          = new ZipFile();
                zip1.FullScan = true;
                zip1.Initialize(zipFileName);

                zip2 = ZipFile.Read(zipFileName);

                foreach (var e1 in zip1)
                {
                    foreach (var e2 in zip2)
                    {
                        if (e1.FileName == e2.FileName)
                        {
                            if (e1._RelativeOffsetOfLocalHeader != e2._RelativeOffsetOfLocalHeader)
                            {
                                isOk = false;
                                notes.Add(String.Format("{0}: mismatch in RelativeOffsetOfLocalHeader  (0x{1:X16} != 0x{2:X16})",
                                                        e1.FileName, e1._RelativeOffsetOfLocalHeader,
                                                        e2._RelativeOffsetOfLocalHeader));
                            }
                            if (e1._CompressedSize != e2._CompressedSize)
                            {
                                isOk = false;
                                notes.Add(String.Format("{0}: mismatch in CompressedSize  (0x{1:X16} != 0x{2:X16})",
                                                        e1.FileName, e1._CompressedSize,
                                                        e2._CompressedSize));
                            }
                            if (e1._UncompressedSize != e2._UncompressedSize)
                            {
                                isOk = false;
                                notes.Add(String.Format("{0}: mismatch in UncompressedSize  (0x{1:X16} != 0x{2:X16})",
                                                        e1.FileName, e1._UncompressedSize,
                                                        e2._UncompressedSize));
                            }
                            if (e1.CompressionMethod != e2.CompressionMethod)
                            {
                                isOk = false;
                                notes.Add(String.Format("{0}: mismatch in CompressionMethod  (0x{1:X4} != 0x{2:X4})",
                                                        e1.FileName, e1.CompressionMethod,
                                                        e2.CompressionMethod));
                            }
                            if (e1.Crc != e2.Crc)
                            {
                                isOk = false;
                                notes.Add(String.Format("{0}: mismatch in Crc32  (0x{1:X4} != 0x{2:X4})",
                                                        e1.FileName, e1.Crc,
                                                        e2.Crc));
                            }

                            // found a match, so stop the inside loop
                            break;
                        }
                    }
                }

                zip2.Dispose();
                zip2 = null;

                if (!isOk && fixIfNecessary)
                {
                    string newFileName = Path.GetFileNameWithoutExtension(zipFileName);
                    newFileName = System.String.Format("{0}_fixed.zip", newFileName);
                    zip1.Save(newFileName);
                }
            }
            finally
            {
                if (zip1 != null)
                {
                    zip1.Dispose();
                }
                if (zip2 != null)
                {
                    zip2.Dispose();
                }
            }
            messages = notes.AsReadOnly(); // may or may not be empty
            return(isOk);
        }
Example #43
0
 public string unzipFile(string fileToUnzip, string targetFolder)
 {
     // targetFolder = "C:\\O2\\_tempDir\\tmp10BA_aa";
     try
     {
         PublicDI.log.info("UnZiping file {0} into folder {1}", fileToUnzip, targetFolder);
         Files.checkIfDirectoryExistsAndCreateIfNot(targetFolder);
         var zpZipFile = new ZipFile(fileToUnzip);
         //zpZipFile.ExtractAll(targetFolder, true);
         zpZipFile.ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently;
         //var test = zpZipFile.OutputUsedZip64;
         zpZipFile.ExtractAll(targetFolder);
         zpZipFile.Dispose();
         return targetFolder;
     }
     catch (Exception ex)
     {
         ex.log("in unzipFile: {0} -> {1}".format(fileToUnzip, targetFolder));
         return "";
     }
 }
Example #44
0
        private void CreateArchiveFile(ZipOptions options)
        {
            ZipFile zip = null;
            try
            {
                zip = new ZipFile(Encoding.GetEncoding(866)) // кодировку НЕ МЕНЯТЬ !!!
                {
                    CompressionLevel = options.CompressionLevel,
                    UseZip64WhenSaving = options.Zip64,
                };

                zip.AddDirectory(options.Files, Consts.FileData);
                zip.AddFile(options.Database, "");

                zip.SaveProgress += this.SaveProgress;

                zip.Save(options.Archive);
            }
            finally
            {
                if (zip != null)
                    zip.Dispose();
            }
        }
Example #45
0
        /// <summary>
        /// Streams a local zip file using a streamreader.
        /// Important: the caller must call Dispose() on the returned ZipFile instance.
        /// </summary>
        /// <param name="filename">Location of the original zip file</param>
        /// <param name="zip">The ZipFile instance to be returned to the caller</param>
        /// <returns>Stream reader of the first file contents in the zip file</returns>
        public static StreamReader Unzip(string filename, out ZipFile zip)
        {
            StreamReader reader = null;
            zip = null;

            try
            {
                if (File.Exists(filename))
                {
                    try
                    {
                        zip = new ZipFile(filename);

                        reader = new StreamReader(zip[0].OpenReader());
                    }
                    catch (Exception err)
                    {
                        Log.Error("QC.Data.Unzip(1): " + err.Message);
                        if (zip != null) zip.Dispose();
                        if (reader != null) reader.Close();
                    }
                }
                else
                {
                    Log.Error("Data.UnZip(2): File doesn't exist: " + filename);
                }
            }
            catch (Exception err)
            {
                Log.Error("Data.UnZip(3): " + filename + " >> " + err.Message);
            }
            return reader;
        }
Example #46
0
        /// <summary>
        /// Выполяем восстановление архива
        /// </summary>
        /// <param name="archiveName"></param>
        private void RestoreDataFromArchive(string archiveName, string databaseFileName, string filesFolderName)
        {
            ZipFile zip = null;
            try
            {
                zip = new ZipFile(archiveName, Encoding.GetEncoding(866));
                zip.ExtractProgress += ExtractingProgress;

                entriesExtractedTotal = zip.Entries.Count;
                entriesExtracted = 0;

                // Ищем в архиве файл MitsarDataStudio.mdb
                var database = zip.Entries.Where(e => e.FileName.StartsWith(Consts.MitsarDataStudio) && e.IsDirectory == false).FirstOrDefault();

                if (database != null)
                {
                    database.FileName = Path.GetFileName(databaseFileName);
                    string path = Path.GetDirectoryName(databaseFileName);
                    if (String.IsNullOrEmpty(path) == false)
                        database.Extract(path, ExtractExistingFileAction.OverwriteSilently);
                    else
                        database.Extract(ExtractExistingFileAction.OverwriteSilently);
                }
                else
                {
                    throw new Exception(Strings.Exception_MitsarDataStudioMdbIsNotFound);
                }

                entriesExtracted++;
                // Ищем в архиве FileData
                var files = zip.Entries
                    .Where(e => e.FileName.StartsWith(Consts.FileData))
                    .SkipWhile(e => String.IsNullOrEmpty(Path.GetFileName(e.FileName)) == true);

                if (files != null)
                {
                    files.ToList().ForEach(e =>
                    {
                        e.FileName = Path.GetFileName(e.FileName);
                        e.Extract(filesFolderName, ExtractExistingFileAction.OverwriteSilently);
                        entriesExtracted++;

                    });
                }
                else
                {
                    throw new Exception(Strings.Exception_FileDataFolderIsNotFound);
                }

            }
            finally
            {
                if (zip != null)
                    zip.Dispose();
            }
        }