FastZip provides facilities for creating and extracting zip files.
        internal static bool ExtractArchive(string archive, string destination)
        {

            //REFACTOR: Only create RAR and ZIP classes after discovering that the file actually has a .zip or .rar extension
            FileInfo archiveFI = new FileInfo(archive);
            Rar rar = new Rar();
            FastZip fz = new FastZip();

            double archivesize = archiveFI.Length * 2;
            char driveLetter = archiveFI.FullName[0];


            if (!CheckDiskSpaceQuota(archivesize, driveLetter)) return false;


            if (archiveFI.Extension == ".rar" || archiveFI.Extension == ".RAR")
                return ExtractRarArchive(archive, destination, archiveFI, rar);

            // ReSharper disable ConvertIfStatementToReturnStatement
            if (archiveFI.Extension == ".zip" || archiveFI.Extension == ".ZIP")
            // ReSharper restore ConvertIfStatementToReturnStatement
                return ExtractZipArchive(archive, destination, fz);

            //TODO: Should this return false?
            return true;

        }
示例#2
1
        public Program()
        {
            string[] dirs=Directory.GetDirectories(".");
            foreach (string dir in dirs)
            {

                DataBase.AnimatedBitmap an = new DataBase.AnimatedBitmap();
                an._Name =Path.GetFileName(dir);
                foreach (string file in Directory.GetFiles(dir))
                    if (Regex.IsMatch(Path.GetExtension(file), "jpg|png", RegexOptions.IgnoreCase))
                        an._Bitmaps.Add(file.Replace(@"\", "/","./",""));

                if (an._Bitmaps.Count > 0)
                {
                    Image img = Bitmap.FromFile(an._Bitmaps.First());
                    an._Width = img.Width;
                    an._Height = img.Height;
                    _DataBase._AnimatedBitmaps.Add(an);

                }
            }
            Common._XmlSerializer.Serialize("./db.xml", _DataBase);

            FastZip _FastZip = new FastZip();
            _FastZip.CreateZip("content.zip","./",true,@"\.jpg|\.png|.\xml");
        }
示例#3
1
 /// <summary>
 /// 解压zip文件
 /// </summary>
 /// <param name="_zipFile">需要解压的zip路径+名字</param>
 /// <param name="_outForlder">解压路径</param>
 public void UnZipFile(string _zipFile, string _outForlder)
 {
     if (Directory.Exists(_outForlder))
         Directory.Delete(_outForlder, true);
     Directory.CreateDirectory(_outForlder);
     progress = progressOverall = 0;
     Thread thread = new Thread(delegate ()
     {
         int fileCount = (int)new ZipFile(_zipFile).Count;
         int fileCompleted = 0;
         FastZipEvents events = new FastZipEvents();
         events.Progress = new ProgressHandler((object sender, ProgressEventArgs e) =>
         {
             progress = e.PercentComplete;
             if (progress == 100) { fileCompleted++; progressOverall = 100 * fileCompleted / fileCount; }
         });
         events.ProgressInterval = TimeSpan.FromSeconds(progressUpdateTime);
         events.ProcessFile = new ProcessFileHandler(
             (object sender, ScanEventArgs e) => { });
         FastZip fastZip = new FastZip(events);
         fastZip.ExtractZip(_zipFile, _outForlder, "");
     });
     thread.IsBackground = true;
     thread.Start();
 }
        private static bool ExtractZipArchive(string archive, string destination, FastZip fz)
        {

            DirectoryInfo newdirFI;

            if (!Directory.Exists(destination))
            {
                newdirFI = Directory.CreateDirectory(destination);

                if (!Directory.Exists(newdirFI.FullName))
                {
                    //MessageBox.Show("Directory " + destination + " could not be created.");
                    return false;
                }
            }
            else newdirFI = new DirectoryInfo(destination);


            try
            {
                Thread.Sleep(500);
                fz.ExtractZip(archive, newdirFI.FullName, "");
            }
            catch (Exception e)
            {
                Debugger.LogMessageToFile("The archive " + archive + " could not be extracted to destination " + destination +
                                          ". The following error ocurred: " + e);
            }



            return true;
        }
示例#5
0
文件: Merger.cs 项目: EpicMorg/EMRJT
 private static async Task MergeFile( MergeParams p ) {
     var zf = new FastZip();
     using ( var s = File.OpenWrite( p.DestImg ) ) {
         s.Seek( 0, SeekOrigin.End );
         zf.CreateZip( s, Path.GetDirectoryName( p.DataSource ), false, Path.GetFileName( p.DataSource ), "" );
     }
 }
示例#6
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filename"></param>
        /// <returns>temporary project file name.</returns>
        public string UnzipProject(string filename)
        {
            output = null;
            // Check File
            if (!File.Exists(filename))
                throw new EcellException(string.Format(MessageResources.ErrLoadPrj, filename));

            // Extract zip
            string dir = Path.Combine(Util.GetTmpDir(), Path.GetRandomFileName());
            FastZip fz = new FastZip();
            fz.ExtractZip(filename, dir, null);

            // Check Project File.
            string project = Path.Combine(dir,Constants.fileProjectXML);
            string info = Path.Combine(dir,Constants.fileProjectInfo);
            if(File.Exists(project))
                output = project;
            else if(File.Exists(info))
                output = info;

            if (output == null)
            {
                Directory.Delete(dir);
                throw new EcellException(string.Format(MessageResources.ErrLoadPrj, filename));
            }

            // Return project path.
            return output;
        }
示例#7
0
文件: Backup.cs 项目: Rawwar13/YAMS
        public static void BackupNow(MCServer s)
        {
            Database.AddLog("Backing up " + s.ServerTitle, "backup");

            //Check for a backup dir and create if not
            if (!Directory.Exists(s.ServerDirectory + @"\backups\")) Directory.CreateDirectory(s.ServerDirectory + @"\backups\");

            //Force a save
            s.Save();
            s.DisableSaving();

            //Copy world to a temp Dir
            if (Directory.Exists(Core.StoragePath + s.ServerID.ToString() + @"\backups\temp\")) Directory.Delete(Core.StoragePath + s.ServerID.ToString() + @"\backups\temp\", true);
            if (!Directory.Exists(Core.StoragePath + s.ServerID.ToString() + @"\backups\temp\")) Directory.CreateDirectory(Core.StoragePath + s.ServerID.ToString() + @"\backups\temp\");
            Util.Copy(s.ServerDirectory + @"\world\", s.ServerDirectory + @"\backups\temp\");

            //Re-enable saving then force another save
            s.EnableSaving();
            s.Save();

            //Now zip up temp dir and move to backups
            FastZip z = new FastZip();
            z.CreateEmptyDirectories = true;
            z.CreateZip(s.ServerDirectory + @"\backups\" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "-" + DateTime.Now.Hour + "-" + DateTime.Now.Minute + ".zip", s.ServerDirectory + @"\backups\temp\", true, "");

            //If the server is empty, reset the HasChanged
            if (s.Players.Count == 0) s.HasChanged = false;
        }
示例#8
0
 public void gerarZipDiretorio(string sDiretorioOrigem, string sDiretorioDestino)
 {
     FastZip sz = new FastZip();
     try
     {
         string sArquivoZip = string.Empty;
         //Aqui vou criar um nome do arquivo.
         DateTime newDate = DateTime.Now;
         sArquivoZip = "MeuZip_" + Convert.ToString(newDate).Replace("/", "_").Replace(":", "") + ".zip";
         //Só um tratamento para garantir mais estabilidade
         if (sDiretorioOrigem.Substring(sDiretorioOrigem.Length - 2) != "\\" || sDiretorioDestino.Substring(sDiretorioDestino.Length - 2) != "\\")
         {
             sDiretorioOrigem = sDiretorioOrigem + "\\";
         }
         sz.Password = txtDiretorioZipSenha.Text;
         //Gera o ZIP
         sz.CreateZip(sDiretorioDestino + sArquivoZip, sDiretorioOrigem + "" + "\\", true, "", "");
     }
     catch (Exception ex)
     {
         MessageBox.Show("Ocorreu um erro durante o processo de compactação : " + ex);
     }
     finally
     {
         //Limpa o Objeto
         sz = null;
     }
 }
示例#9
0
        private static void DownloadAndUpdateSnakeBite(string URL)
        {
            // Download update archive
            using (WebClient w = new WebClient()) w.DownloadFile(URL, "update.dat");

            // Extract archive
            FastZip z = new FastZip();
            z.ExtractZip("update.dat", "_update", "(.*?)");

            // Move update file
            File.Delete("SnakeBite.exe");
            File.Delete("MakeBite.exe");
            File.Delete("GzsTool.Core.dll");
            File.Delete("fpk_dictionary.txt");
            File.Delete("qar_dictionary.txt");
            File.Move("_update/SnakeBite.exe", "SnakeBite.exe");
            File.Move("_update/MakeBite.exe", "MakeBite.exe");
            File.Move("_update/GzsTool.Core.dll", "GzsTool.Core.dll");
            File.Move("_update/fpk_dictionary.txt", "fpk_dictionary.txt");
            File.Move("_update/qar_dictionary.txt", "qar_dictionary.txt");

            // Restart updater
            Process updater = new Process();
            updater.StartInfo.Arguments = "-u";
            updater.StartInfo.UseShellExecute = false;
            updater.StartInfo.FileName = "sbupdater.exe";
            updater.Start();

            Environment.Exit(0);
        }
示例#10
0
文件: Zip.cs 项目: jacean/RingsII
        public static void unZIP(string srcZip, string detDir)
        {
            string filename = Path.GetFileNameWithoutExtension(srcZip);
            if (detDir == string.Empty)
            {
                detDir = srcZip.Substring(0,srcZip.LastIndexOf("\\"));
            }

            detDir = detDir + "\\" + filename;

            if (!Directory.Exists(detDir))
            {
                 Directory.CreateDirectory(detDir);
            }
            FastZip fastzip = new FastZip();
            //// Create Empty Directory
            fastzip.CreateEmptyDirectories = true;

            try
            {
                fastzip.ExtractZip(srcZip, detDir, string.Empty);
                //MessageBox.Show("ok");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
示例#11
0
        private void buttonCreateBackup_Click(object sender, EventArgs e)
        {
            if (Directory.Exists("_backup")) Directory.Delete("_backup", true);
            Directory.CreateDirectory("_backup");

            // prompt user for backup filename
            SaveFileDialog saveBackup = new SaveFileDialog();
            saveBackup.Filter = "SnakeBite Backup|*.sbb";
            DialogResult saveResult = saveBackup.ShowDialog();
            if (saveResult != DialogResult.OK) return;

            // copy current settings
            objSettings.SaveSettings();
            File.Copy(ModManager.GameDir + "\\sbmods.xml", "_backup\\sbmods.xml");

            // copy current 01.dat
            File.Copy(ModManager.GameArchivePath, "_backup\\01.dat");

            // compress to backup
            FastZip zipper = new FastZip();
            zipper.CreateZip(saveBackup.FileName, "_backup", true, "(.*?)");

            Directory.Delete("_backup", true);

            MessageBox.Show("Backup complete.", "SnakeBite", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
 private void UnzipNewAgentVersion()
 {
     _logger.Log("Unzipping files");
     var fz = new FastZip();
     fz.ExtractZip(Constants.AgentServiceReleasePackage, Constants.AgentServiceUnzipPath, "");
     _logger.Log("Unzipping files complete");
 }
示例#13
0
 /// <summary>
 /// Writes the specified directory to a new zip file.
 /// </summary>
 /// <param name="sourceDirectory">Directory with files to add.</param>
 /// <param name="zipFileName">Output file name.</param>
 public static void Zip(string sourceDirectory, string zipFileName)
 {
     FastZip fastZip = new FastZip();
     fastZip.RestoreAttributesOnExtract = true;
     fastZip.RestoreDateTimeOnExtract = true;
     fastZip.CreateZip(zipFileName, sourceDirectory, true, null);
 }
示例#14
0
    /// <summary>压缩文件</summary>
    /// <param name="filename">filename生成的文件的名称,如:C:\RAR\075_20110820153200001-1.rar</param>
    /// <param name="directory">directory要压缩的文件夹路径,如:C:\OA</param>
    /// <returns></returns>
    public static bool PackFiles(string filename, string directory)
    {
        try
        {

            directory = directory.Replace("/", "\\");

            if (!directory.EndsWith("\\"))
                directory += "\\";
            if (!System.IO.Directory.Exists(directory))
            {
                System.IO.Directory.CreateDirectory(directory);
            }
            if (System.IO.File.Exists(filename))
            {
                System.IO.File.Delete(filename);
            }
            FastZip fz = new FastZip();
            fz.CreateEmptyDirectories = true;
            fz.CreateZip(filename, directory, true, "");
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        //try
        //{
        string zipFileName = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\OSAE\OSA_Logs.zip";

            FastZip fastZip = new FastZip();
            if (File.Exists(zipFileName))
                File.Delete(zipFileName);

            fastZip.CreateZip(zipFileName, Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\OSAE\Logs", true, "");

            Response.Clear();
            Response.ClearHeaders();
            Response.ClearContent();
            Response.AddHeader("Content-Disposition", "attachment; filename=OSA_Logs.zip");
            Response.AddHeader("Content-Length", new FileInfo(zipFileName).Length.ToString());
            Response.ContentType = "application/octet-stream";
            Response.Flush();
            Response.TransmitFile(zipFileName);
            Response.End();
        ///}
        //catch (Exception ex)
        //{
            // not going to do anything as the file may be in use so just carry on
        //}
    }
示例#16
0
        public void Basics()
        {
            const string tempName1 = "a(1).dat";

            MemoryStream target = new MemoryStream();

            string tempFilePath = GetTempFilePath();
            Assert.IsNotNull(tempFilePath, "No permission to execute this test?");

            string addFile = Path.Combine(tempFilePath, tempName1);
            MakeTempFile(addFile, 1);

            try {
                FastZip fastZip = new FastZip();
                fastZip.CreateZip(target, tempFilePath, false, @"a\(1\)\.dat", null);

                MemoryStream archive = new MemoryStream(target.ToArray());
                using (ZipFile zf = new ZipFile(archive)) {
                    Assert.AreEqual(1, zf.Count);
                    ZipEntry entry = zf[0];
                    Assert.AreEqual(tempName1, entry.Name);
                    Assert.AreEqual(1, entry.Size);
                    Assert.IsTrue(zf.TestArchive(true));

                    zf.Close();
                }
            }
            finally {
                File.Delete(tempName1);
            }
        }
示例#17
0
文件: Scheduler.cs 项目: LeGrin/NYSub
 private void GetFile()
 {
     var exctractfolder = _localFile.DirectoryName.ToString() + @"\exctract\";
     DownloadFile(_localFile.FullName);
     var zip = new FastZip();
     zip.ExtractZip(_localFile.FullName, exctractfolder, "");
 }
示例#18
0
 public static  void ZipDir(string strDir, string strZipFile)
 {
     FastZip fz = new FastZip();
     fz.CreateEmptyDirectories = true;
     fz.CreateZip(strZipFile, strDir, true, "");
     fz = null;
 }
示例#19
0
        public static Boolean ZipFolder(String folder, String zipFile)
        {
            if (!Directory.Exists(folder))
            {
                Debug.WriteLine("Cannot find directory '{0}'", folder);
                return(false);
            }

            try
            {
                ICSharpCode.SharpZipLib.Zip.FastZip z = new ICSharpCode.SharpZipLib.Zip.FastZip();
                z.CreateEmptyDirectories = true;
                z.CreateZip(zipFile, folder, true, "");

                if (File.Exists(zipFile))
                {
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception during processing {0}", ex);
            }
            return(false);
        }
示例#20
0
        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SavePangyaPicture("front", FrontImg);
            SavePangyaPicture("back", BackImg);

            bool existsicon = System.IO.File.Exists("C:\\Windows\\Temp\\davedevils\\" + ActualFileSD + "\\icon");

            if (existsicon)
            {
                SavePangyaPicture("icon", IconImg);
            }

            ICSharpCode.SharpZipLib.Zip.FastZip z = new ICSharpCode.SharpZipLib.Zip.FastZip();
            z.CreateEmptyDirectories = false;
            z.CreateZip(ActualFileSD + ".jpg", "C:\\Windows\\Temp\\davedevils\\" + ActualFileSD, true, "");

            if (File.Exists(ActualFileSD + ".jpg"))
            {
                MessageBox.Show("Saved at " + ActualFileSD + ".jpg");
            }
            else
            {
                MessageBox.Show("Save has fail :(");
            }
        }
示例#21
0
文件: Backup.cs 项目: rusnewman/YAMS
        public static void BackupNow(MCServer s, string strAppendName = "")
        {
            Database.AddLog("Backing up " + s.ServerTitle, "backup");

            //Check for a backup dir and create if not
            if (!Directory.Exists(s.ServerDirectory + @"\backups\")) Directory.CreateDirectory(s.ServerDirectory + @"\backups\");

            //Force a save
            s.Save();
            s.DisableSaving();

            //Find all the directories that start with "world"
            if (Directory.Exists(Core.StoragePath + s.ServerID.ToString() + @"\backups\temp\")) Directory.Delete(Core.StoragePath + s.ServerID.ToString() + @"\backups\temp\", true);
            if (!Directory.Exists(Core.StoragePath + s.ServerID.ToString() + @"\backups\temp\")) Directory.CreateDirectory(Core.StoragePath + s.ServerID.ToString() + @"\backups\temp\");

            string[] dirs = Directory.GetDirectories(s.ServerDirectory, "world*");
            foreach (string dir in dirs)
            {
                //Copy world to a temp Dir
                DirectoryInfo thisDir = new DirectoryInfo(dir);
                Util.Copy(dir, s.ServerDirectory + @"\backups\temp\" + thisDir.Name);
            }

            //Re-enable saving then force another save
            s.EnableSaving();
            s.Save();

            //Now zip up temp dir and move to backups
            FastZip z = new FastZip();
            z.CreateEmptyDirectories = true;
            z.CreateZip(s.ServerDirectory + @"\backups\" + DateTime.Now.Year + "-" + DateTime.Now.Month.ToString("D2") + "-" + DateTime.Now.Day.ToString("D2") + "-" + DateTime.Now.Hour.ToString("D2") + "-" + DateTime.Now.Minute.ToString("D2") + strAppendName + ".zip", s.ServerDirectory + @"\backups\temp\", true, "");

            //If the server is empty, reset the HasChanged
            if (s.Players.Count == 0) s.HasChanged = false;
        }
示例#22
0
 /// <summary>
 /// 压缩文件夹
 /// </summary>
 /// <param name="_fileForlder">文件夹路径</param>
 /// <param name="_outZip">zip文件路径+名字</param>
 public void ZipFolder(string _fileFolder, string _outZip)
 {
     string directory = _outZip.Substring(0, _outZip.LastIndexOf('/'));
     if (!Directory.Exists(directory))
         Directory.CreateDirectory(directory);
     if (File.Exists(_outZip))
         File.Delete(_outZip);
     progress = progressOverall = 0;
     Thread thread = new Thread(delegate ()
     {
         int fileCount = FileCount(_fileFolder);
         int fileCompleted = 0;
         FastZipEvents events = new FastZipEvents();
         events.Progress = new ProgressHandler((object sender, ProgressEventArgs e) =>
         {
             progress = e.PercentComplete;
             if (progress == 100) { fileCompleted++; progressOverall = 100 * fileCompleted / fileCount; }
         });
         events.ProgressInterval = TimeSpan.FromSeconds(progressUpdateTime);
         events.ProcessFile = new ProcessFileHandler(
             (object sender, ScanEventArgs e) => { });
         FastZip fastZip = new FastZip(events);
         fastZip.CreateZip(_outZip, _fileFolder, true, "");
     });
     thread.IsBackground = true;
     thread.Start();
 }
示例#23
0
        public ReleasePackage CreateDeltaPackage(ReleasePackage basePackage, ReleasePackage newPackage, string outputFile)
        {
            Contract.Requires(basePackage != null);
            Contract.Requires(!String.IsNullOrEmpty(outputFile) && !File.Exists(outputFile));

            if (basePackage.Version > newPackage.Version) {
                var message = String.Format(
                    "You cannot create a delta package based on version {0} as it is a later version than {1}",
                    basePackage.Version,
                    newPackage.Version);
                throw new InvalidOperationException(message);
            }

            if (basePackage.ReleasePackageFile == null) {
                throw new ArgumentException("The base package's release file is null", "basePackage");
            }

            if (!File.Exists(basePackage.ReleasePackageFile)) {
                throw new FileNotFoundException("The base package release does not exist", basePackage.ReleasePackageFile);
            }

            if (!File.Exists(newPackage.ReleasePackageFile)) {
                throw new FileNotFoundException("The new package release does not exist", newPackage.ReleasePackageFile);
            }

            string baseTempPath = null;
            string tempPath = null;

            using (Utility.WithTempDirectory(out baseTempPath, null))
            using (Utility.WithTempDirectory(out tempPath, null)) {
                var baseTempInfo = new DirectoryInfo(baseTempPath);
                var tempInfo = new DirectoryInfo(tempPath);

                this.Log().Info("Extracting {0} and {1} into {2}", 
                    basePackage.ReleasePackageFile, newPackage.ReleasePackageFile, tempPath);

                var fz = new FastZip();
                fz.ExtractZip(basePackage.ReleasePackageFile, baseTempInfo.FullName, null);
                fz.ExtractZip(newPackage.ReleasePackageFile, tempInfo.FullName, null);

                // Collect a list of relative paths under 'lib' and map them
                // to their full name. We'll use this later to determine in
                // the new version of the package whether the file exists or
                // not.
                var baseLibFiles = baseTempInfo.GetAllFilesRecursively()
                    .Where(x => x.FullName.ToLowerInvariant().Contains("lib" + Path.DirectorySeparatorChar))
                    .ToDictionary(k => k.FullName.Replace(baseTempInfo.FullName, ""), v => v.FullName);

                var newLibDir = tempInfo.GetDirectories().First(x => x.Name.ToLowerInvariant() == "lib");

                foreach (var libFile in newLibDir.GetAllFilesRecursively()) {
                    createDeltaForSingleFile(libFile, tempInfo, baseLibFiles);
                }

                ReleasePackage.addDeltaFilesToContentTypes(tempInfo.FullName);
                fz.CreateZip(outputFile, tempInfo.FullName, true, null);
            }

            return new ReleasePackage(outputFile);
        }
示例#24
0
        private static void Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.Error.WriteLine("Error: not enough arguments");
                Console.Error.WriteLine("Usage: MetroIdeUpdateManager <update zip> <metroide exe> <parent pid>");
                return;
            }
            string zipPath = args[0];
            string exePath = args[1];
            int pid = Convert.ToInt32(args[2]);

            try
            {
                // Wait for Assembly to close
                try
                {
                    Process process = Process.GetProcessById(pid);
                    process.WaitForExit();
                    process.Close();
                }
                catch
                {
                }

                // Extract the update zip
                var fz = new FastZip {CreateEmptyDirectories = true};
                for (int i = 0; i < 5; i++)
                {
                    try
                    {
                        fz.ExtractZip(zipPath, Directory.GetCurrentDirectory(), null);
                        break;
                    }
                    catch (IOException)
                    {
                        Thread.Sleep(1000);
                        if (i == 4)
                        {
                            throw;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Assembly Update Manager", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            try
            {
                File.Delete(zipPath);
            }
            catch
            {
            }

            // Launch "The New iPa... Assembly"
            Process.Start("Assembly://post-update");
        }
        private void ChoosePackageDialog()
        {
            // Configure open file dialog box 
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.FileName = "Document"; // Default file name 
            dlg.DefaultExt = ".AGT"; // Default file extension 
            dlg.Filter = "Agent Package (.agt)|*.agt"; // Filter files by extension 

            // Show open file dialog box 
            Nullable<bool> result = dlg.ShowDialog();

            // Process open file dialog box results 
            if (result == true)
            {
                // Open document 
                PackageSource = dlg.FileName;

                ICSharpCode.SharpZipLib.Zip.FastZip fz = new FastZip();

                var root = System.IO.Path.Combine(System.IO.Path.GetTempPath(), (Guid.NewGuid().ToString()));

                fz.ExtractZip(PackageSource, root, FastZip.Overwrite.Always, null, null, null, true);

                PackageFile = System.IO.Path.Combine(root, "package.json");

                if (System.IO.File.Exists(PackageFile))
                {
                    var cnt =  System.IO.File.ReadAllText(PackageFile);
                    Contents = cnt;
                }
            }
        }
示例#26
0
		private void setDbfInfoFromZip(string dbfPath)
		{	
			try
			{	
				//Navigate the Zip to find the files and update their index
				ZipFile zFile = new ZipFile(dbfPath);				
				foreach (ZipEntry ze in zFile) 
				{
					if(ze.Name.ToLower().EndsWith(".dbf"))
					{
						//Extracts the file in temp
						FastZip fz = new FastZip();
						fz.ExtractZip(dbfPath, Path.GetTempPath(),
							ICSharpCode.SharpZipLib.Zip.FastZip.Overwrite.Always,null,"","");
						setDbfInfo(Path.Combine(Path.GetTempPath(),ze.Name));						
					}
				}						
			}
			catch { return; }			


			

            
			
			//TODO: read the sbf data into the datagrid

			//DataTable dt=getInfoFromDBF(dbfPath);			
			//dataGrid1.DataSource=dt;
			//dataGrid1.CaptionText=dbfPath;			
		}
示例#27
0
    protected void LinkZip_Click(object sender, EventArgs e)
    {
        if (!YetkiKontrol(pageName + "-Update"))
            return;


        try
        {
            string temaPath = Server.MapPath("~/uploads/temp/temp-uploaded");

            try { Directory.Delete(temaPath, true); }
            catch { }

            if (FU1.PostedFile.ContentType != "application/x-zip-compressed" && FU1.PostedFile.ContentType != "application/octet-stream" && FU1.PostedFile.ContentType != "application/zip" && FU1.PostedFile.ContentType != "application/x-rar-compressed")
            {
                Snlg_Hata.ziyaretci.HataGosterHatali(Resources.admin_language.theme_01, false);
                return;
            }
            if (Path.GetExtension(FU1.FileName).ToLower() != ".zip")
            {
                Snlg_Hata.ziyaretci.HataGosterHatali(Resources.admin_language.theme_02, false);
                return;
            }

            FU1.SaveAs(Server.MapPath("~/uploads/temp/temp-tema.zip"));
            FastZip fz = new FastZip();
            fz.ExtractZip(Server.MapPath("~/uploads/temp/temp-tema.zip"), temaPath, null);
            File.Delete(Server.MapPath("~/uploads/temp/temp-tema.zip"));

            bool exist = false;
            StringBuilder sbHtml = new StringBuilder();
            ListExistsFile(temaPath, sbHtml, 0, ref exist, temaPath);

            if (exist)
            {
                LtrList.Text = sbHtml.ToString();
                Snlg_Hata.ziyaretci.HataGosterHatali(Resources.admin_language.theme_03, false);
            }
            else
                Snlg_Hata.ziyaretci.HataGosterBasarili(Resources.admin_language.theme_04, false);

            if (Directory.Exists(Path.Combine(temaPath, "sql-scripts")))
            {
                string[] sqlFiles = Directory.GetFiles(Path.Combine(temaPath, "sql-scripts"), "*.sql");
                if (sqlFiles.Length > 0)
                    Snlg_Hata.ziyaretci.HataGosterUyari(Resources.admin_language.theme_05.Replace("{0}", sqlFiles.Length.ToString()), false);
                else
                    Snlg_Hata.ziyaretci.HataGosterBasarili(Resources.admin_language.theme_06, false);
            }
            else
                Snlg_Hata.ziyaretci.HataGosterBasarili(Resources.admin_language.theme_07, false);

            divButon.Visible = true;
        }
        catch (Exception exc)
        {
            Snlg_Hata.ziyaretci.HataGosterHatali(Resources.admin_language.theme_08 + exc.Message, false);
            return;
        }
    }
示例#28
0
 private void  initZipEvents()
 {
     zip = new FastZip(zipEvents);
     zip.CreateEmptyDirectories = true;
     zipEvents.CompletedFile   += onCompletedFile;
     //zipEvents.ProcessDirectory   += onCompletedDirectory;
 }
示例#29
0
 /// <summary>
 /// Décompresse entierement un fichier LibreOffice
 /// </summary>
 /// <param name="zipFile"></param>
 /// <param name="destination"></param>
 /// <returns></returns>
 public void extractZip(string zipFile, string destination)
 {
     ICSharpCode.SharpZipLib.Zip.FastZip z = new ICSharpCode.SharpZipLib.Zip.FastZip();
     z.CreateEmptyDirectories     = true;
     z.RestoreAttributesOnExtract = true;
     z.RestoreDateTimeOnExtract   = true;
     z.ExtractZip(zipFile, destination, string.Empty);
 }
示例#30
0
        public void UnZip()
        {
            string zipPath = "D:/Test.zip";
            string zipDir = "D:/Test2/";

            FastZip fastZip = new FastZip();
            fastZip.ExtractZip(zipPath, zipDir, null);
        }
示例#31
0
 public void createZip(string source, string zipFile)
 {
     ICSharpCode.SharpZipLib.Zip.FastZip z = new ICSharpCode.SharpZipLib.Zip.FastZip();
     z.CreateEmptyDirectories     = true;
     z.RestoreAttributesOnExtract = true;
     z.RestoreDateTimeOnExtract   = true;
     z.CreateZip(zipFile, source, true, "");
 }
 public static void ExtractZipFile(string zipFile, string outputFolder) {
     FastZip fastZip = new FastZip();
     try {
         fastZip.ExtractZip(zipFile, outputFolder, null); // Will always overwrite if target filenames already exist
     } catch (Exception ex) {
         Logger.Error("Extracting Zip failed.", ex);
     }
 }
示例#33
0
 public static bool ExtractZip(string filename, string directory)
 {
     FastZip fz = new FastZip();
     fz.CreateEmptyDirectories = true;
     fz.ExtractZip(filename, directory, "");
     fz = null;
     return true;
 }
示例#34
0
        private static void Extract(FileInfo file, bool isNestedFolders, out bool status)
        {
            if (file == null)
            {
                status = false;
            }
            else
            {
                var successStatus = false;
                //declares/assigns output directory
                //Build file file path for extraction
                var fileName = Path.Combine(DirPath, file.Name);
                var fastZip = new FastZip();
                try
                {
                    if (!isNestedFolders)
                    {
                        var path = CreateDirectory(file);
                        //extracts file to destination directory
                        switch (CheckFileIfExists(file))
                        {

                            case 0:
                                fastZip.ExtractZip(fileName, path, null);
                                successStatus = true;
                                break;
                            default:
                                successStatus = false;
                                throw new Exception("File Already Exists");
                        }
                    }
                    else
                    {
                        switch (CheckIfDirectoryExists(file, Outfile))
                        {
                            case false:
                                fastZip.ExtractZip(fileName, Outfile, null);
                                successStatus = true;
                                break;
                            default:
                                successStatus = false;
                                throw new Exception("File Already Exists");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    //fails job
                    successStatus = false;
                }
                finally
                {
                    //sets out param after all proccessing has finished
                    status = successStatus;
                }
            }
        }
示例#35
0
        /// <summary>
        /// 解压
        /// </summary>
        public static void decompress(string _localPath, string _zipFileName)
        {
            string zipFileName = _zipFileName; //待解压的目录文件
            string localPath   = _localPath;   //解压后的目录
            // Zip it into a memory stream.
            var zip = new ICSharpCode.SharpZipLib.Zip.FastZip();

            zip.ExtractZip(zipFileName, localPath, string.Empty);
        }
        internal static bool GetSubtitleForVideo(string videoHash, string imdbid,
            string language, string logintoken, IMLItem item,
            string parentPath, string videoFilename, bool isMovie)
        {
            #region  vars
            WebClient webClient = new WebClient();
            webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

            string firstsub = string.Empty;

            FastZip fz = new FastZip();
            #endregion

            if (string.IsNullOrEmpty(parentPath))
                return false;

            if (!parentPath.EndsWith(@"\"))
                parentPath += @"\";

            string zipfilePath = parentPath + videoHash + ".zip";

            try
            {

                firstsub = VideoSubtitleDownloaderHelpers.SearchForSubtitleByVideoHashParent(videoHash, language);

                if (!VideoSubtitleDownloaderHelpers.SearchForSubtitleByIMDbIdParent(imdbid, language,
                    logintoken, item, isMovie, ref firstsub))
                    return false;

                if (!VideoSubtitleDownloaderHelpers.PerformSubtitleDownload(item, zipfilePath, webClient, firstsub))
                    return false;

            }
            catch (Exception e)
            {
                MessageBox.Show(@"An error occured while trying to download
                the subtitle on online address: " + firstsub + @" to local location: "
                + zipfilePath + @". The error was: " + e);

                Debugger.LogMessageToFile("Error occured in subtitles downloading function: "
                    + e + ".  The intented subtitle zip location was: " + zipfilePath +
                    "  and oline subtitle location was: " + firstsub);

                return false;

            }

            if (!VideoSubtitleDownloaderHelpers.ValidateDownloadedDataAndRetry(language, item,
                firstsub, webClient, zipfilePath))
                return false;

            VideoSubtitleDownloaderHelpers.ExtractAndRenameSubtitle(language, item, parentPath,
                videoFilename, zipfilePath, fz);

            return true;
        }
示例#37
0
        public string ZipDirectory(string path)
        {
            string zipPath = path + @"..\" + "空白詢價單.zip";

            ICSharpCode.SharpZipLib.Zip.FastZip z = new ICSharpCode.SharpZipLib.Zip.FastZip();
            z.CreateEmptyDirectories = true;
            z.CreateZip(zipPath, path, true, "");
            return(zipPath);
        }
示例#38
0
    IEnumerator DownloadChart()
    {
        isDownloading = true;
        WWW Download = new WWW(LimSystem.LanotaliumServer + "/lanotalium/chartzone/" + Data.ChartName + "/" + Data.ChartName + ".zip");

        DownloadSlider.value = 0;
        while (!Download.isDone)
        {
            DownloadSlider.value = Download.progress;
            SizeText.text        = (Download.progress * 100).ToString("f2") + "%";
            yield return(null);
        }
        DownloadSlider.value = 1;
        SizeText.text        = "100.00%";
        SizeText.text        = Data.Size;
        byte[] Chart = Download.bytes;
#if UNITY_STANDALONE
        string SavePath = WindowsDialogUtility.SaveFileDialog("", "(.zip)|*.zip", Data.ChartName + ".zip");
        if (SavePath == null)
        {
            yield break;
        }
        File.WriteAllBytes(SavePath, Chart);
        Process.Start("explorer.exe", "/select," + SavePath.Replace("/", "\\"));
#endif
#if UNITY_IOS
        string SaveDirectory = UnityEngine.Application.persistentDataPath + "/chartzone/" + Data.ChartName;
        string SavePath      = UnityEngine.Application.persistentDataPath + "/chartzone/" + Data.ChartName + "/" + Data.ChartName + ".zip";
        Directory.CreateDirectory(Directory.GetParent(SavePath).FullName);
        File.WriteAllBytes(SavePath, Chart);
        ICSharpCode.SharpZipLib.Zip.FastZip fastZip = new ICSharpCode.SharpZipLib.Zip.FastZip();
        Task ExtractTask = new Task(() => fastZip.ExtractZip(SavePath, SaveDirectory, ""));
        ExtractTask.Start();
        while (ExtractTask.Status == TaskStatus.Running)
        {
            yield return(null);
        }
        Lanotalium.Project.LanotaliumProject lanotaliumProject = new Lanotalium.Project.LanotaliumProject
        {
            Name      = Data.ChartName,
            Designer  = Data.Designer,
            BGA0Path  = SaveDirectory + "/background0.png",
            ChartPath = SaveDirectory + "/chart.txt",
            MusicPath = SaveDirectory + "/music.ogg"
        };
        File.WriteAllText(SaveDirectory + "/project.lap", Newtonsoft.Json.JsonConvert.SerializeObject(lanotaliumProject));
        LimChartZoneManager.OpenDownloadedChart    = true;
        LimChartZoneManager.DownloadedChartLapPath = SaveDirectory + "/project.lap";
        isDownloading = false;
        SceneManager.LoadScene("LimTuner");
#endif
        isDownloading = false;
    }
示例#39
0
        /// <summary>
        /// 压缩
        /// </summary>
        /// <param name="_localPath">待压缩的目录或文件</param>
        /// <param name="_zipFileName">压缩后的目录文件</param>
        public static void compress(string _localPath, string _zipFileName)
        {
            string localPath   = _localPath;   //待压缩的目录或文件
            string zipFileName = _zipFileName; //压缩后的目录文件
            // Export the directory tree from SVN server.
            //localPath = System.IO.Path.Combine(localPath, Guid.NewGuid().ToString());
            // Zip it into a memory stream.

            var zip = new ICSharpCode.SharpZipLib.Zip.FastZip();

            zip.CreateZip(zipFileName, localPath, true, string.Empty, string.Empty);
        }
示例#40
0
    private void UnZipFiles(FileUpload fpAttach, string NewID)
    {
        string path = ConfigurationManager.AppSettings["FilePath"].ToString();

        string UlFileName = "";

        string[] filetype = fpAttach.FileName.Split('.');

        ICSharpCode.SharpZipLib.Zip.FastZip myZip = new ICSharpCode.SharpZipLib.Zip.FastZip();

        UlFileName = path + NewID + "." + filetype[1].ToString();
        Page sv = new Page();

        myZip.ExtractZip(sv.Server.MapPath(UlFileName), sv.Server.MapPath("~/Temp/" + NewID), "");
    }
示例#41
0
    /// <summary>
    /// 创建补丁
    /// </summary>
    /// <param name="path">差异化文件路径</param>
    /// <param name="suffix">附加后缀</param>
    /// <param name="compress">是否压缩</param>
    /// <param name="onStep"></param>
    /// <param name="onEnd"></param>
    public void CreatePatch(List <string> path, string prefix, string suffix, bool compress = false, Action <int, int> onStep = null, Action <string> onEnd = null)
    {
        if (string.IsNullOrEmpty(Info.DiffPatchPath))
        {
            if (onEnd != null)
            {
                onEnd.Invoke("");
            }
            return;
        }
        ;
        string targetPath = Path.Combine(Info.DiffPatchPath, string.Format("{0}_{1}_{2}_{3}", prefix, Info.LastVersion, DateTime.Now.ToString("yyyyMMdd-HHmm-ss"), suffix));

        if (Directory.Exists(targetPath))
        {
            Directory.Delete(targetPath, true);
        }
        Directory.CreateDirectory(targetPath);
        Thread thread = new Thread(new ThreadStart(() =>
        {
            string tempPath;
            for (int i = 0; i < path.Count; i++)
            {
                if (onStep != null)
                {
                    onStep.Invoke(i, path.Count);
                }
                tempPath = Info.CreatePatchUseLeftFile.Contains(path[i]) ? GetLeftPathByRightPath(Info.LeftComprePath, Info.RightComprePath, path[i]) : path[i];
                Copy(tempPath, GetLeftPathByRightPath(targetPath, Info.RightComprePath, path[i]));
            }
            if (compress)
            {
                ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
                zip.CreateZip(targetPath + ".zip", targetPath, true, "");
                Directory.Delete(targetPath, true);
                if (onEnd != null)
                {
                    onEnd.Invoke(Path.GetDirectoryName(targetPath));
                }
            }
            else if (onEnd != null)
            {
                onEnd.Invoke(targetPath);
            }
        }));

        thread.Start();
    }
示例#42
0
        /// <summary>
        /// 转换
        /// </summary>
        /// <param name="sourceFile"></param>
        /// <param name="dest"></param>
        /// <returns></returns>
        public override List <string> DoDecompress(string sourceFile, string dest)
        {
            var result = Decompress(sourceFile, DestDirectory);

            return(result);

            if (false)
            {
                System.IO.Compression.ZipFile.ExtractToDirectory(sourceFile, DestDirectory);
            }

            if (false)
            {
                ICSharpCode.SharpZipLib.Zip.FastZip fastZip = new ICSharpCode.SharpZipLib.Zip.FastZip();
                if (!String.IsNullOrEmpty(Password))
                {
                    fastZip.Password = Password;
                }
                fastZip.ExtractZip(sourceFile, DestDirectory, "");
            }
        }
    protected void Run(bool viewListOnly)
    {
        bool debugMode = true;

        int bulkLetterSendingQueueBatchID = !viewListOnly && UseBulkLetterSender?BulkLetterSendingQueueBatchDB.Insert(DebugEmail, false) : -1;

        //
        //  We can not send email all their patients in one email - will be too big with attachments and rejected by their mail provider
        //  So if via email - need to send one at a time
        //  Then if cuts out or times out, it has processed some so don't need to re-process those when it's run again
        //
        //  just remember to process the emails first ... so if any interruptions/errors ... at least some will have been processed
        //



        try
        {
            bool AutoSendFaxesAsEmailsIfNoEmailExistsToGPs = Convert.ToInt32(SystemVariableDB.GetByDescr("AutoSendFaxesAsEmailsIfNoEmailExistsToGPs").Value) == 1;

            string sendMethod = rdioSendType.SelectedValue;
            if (!viewListOnly && SelectedSendMethod == SendMethod.None)
            {
                throw new CustomMessageException("Send method not selected");
            }

            string tmpLettersDirectory = Letter.GetTempLettersDirectory();
            if (!Directory.Exists(tmpLettersDirectory))
            {
                throw new CustomMessageException("Temp letters directory doesn't exist");
            }


            string debugOutput = string.Empty;
            int    startTime   = Environment.TickCount;



            // NB.
            // start/emd date time __must__ refer to the treatment date because
            // as a letter can be generated any time (days or weeks) after a treatment, there is no way
            // to be sure which invoice it is attached to, only which booking
            if (txtStartDate.Text.Length > 0 && !Utilities.IsValidDate(txtStartDate.Text, "dd-mm-yyyy"))
            {
                throw new CustomMessageException("Start date must be empty or valid and of the format dd-mm-yyyy");
            }
            if (txtEndDate.Text.Length > 0 && !Utilities.IsValidDate(txtEndDate.Text, "dd-mm-yyyy"))
            {
                throw new CustomMessageException("End date must be empty or valid and of the format dd-mm-yyyy");
            }
            DateTime startDate = txtStartDate.Text.Length == 0 ? DateTime.MinValue : Utilities.GetDate(txtStartDate.Text, "dd-mm-yyyy");
            DateTime endDate   = txtEndDate.Text.Length == 0 ? DateTime.MinValue : Utilities.GetDate(txtEndDate.Text, "dd-mm-yyyy");


            DataTable bookingsWithSentLetters = BookingDB.GetBookingsWithEPCLetters(startDate, endDate, Convert.ToInt32(registerReferrerID.Value), Convert.ToInt32(patientID.Value), true, false);

            if (!viewListOnly && bookingsWithSentLetters.Rows.Count > MaxSending)
            {
                throw new CustomMessageException("Can not generate more than " + MaxSending + " letters at a time. Please narrow your date range.");
            }

            double queryExecutionTime = (double)(Environment.TickCount - startTime) / 1000.0;
            startTime = Environment.TickCount;


            ArrayList filesToPrint = new ArrayList();

            int       currentRegReferrerID       = -1;
            ArrayList bookingsForCurrentReferrer = new ArrayList();
            foreach (DataRow row in bookingsWithSentLetters.Rows)
            {
                Tuple <Booking, PatientReferrer, bool, bool, HealthCard> rowData = LoadRow(row);
                Booking         booking     = rowData.Item1;
                PatientReferrer pr          = rowData.Item2;
                bool            refHasEmail = rowData.Item3;
                bool            refHasFax   = rowData.Item4;
                HealthCard      hc          = rowData.Item5;


                if (pr.RegisterReferrer.RegisterReferrerID != currentRegReferrerID)
                {
                    filesToPrint.AddRange(ProcessReferrersLetters(viewListOnly, bookingsForCurrentReferrer, AutoSendFaxesAsEmailsIfNoEmailExistsToGPs, ref debugOutput, bulkLetterSendingQueueBatchID));
                    currentRegReferrerID       = pr.RegisterReferrer.RegisterReferrerID;
                    bookingsForCurrentReferrer = new ArrayList();
                }

                bookingsForCurrentReferrer.Add(rowData);
            }

            // process last group
            filesToPrint.AddRange(ProcessReferrersLetters(viewListOnly, bookingsForCurrentReferrer, AutoSendFaxesAsEmailsIfNoEmailExistsToGPs, ref debugOutput, bulkLetterSendingQueueBatchID));



            bool zipSeperately = true;

            if (zipSeperately && filesToPrint.Count > 0)
            {
                // seperate into doc types because can only merge docs with docs of same template (ie docname)
                Hashtable filesToPrintHash = new Hashtable();
                for (int i = 0; i < filesToPrint.Count; i++)
                {
                    Letter.FileContents curFileContents = (Letter.FileContents)filesToPrint[i];
                    if (filesToPrintHash[curFileContents.DocName] == null)
                    {
                        filesToPrintHash[curFileContents.DocName] = new ArrayList();
                    }
                    ((ArrayList)filesToPrintHash[curFileContents.DocName]).Add(curFileContents);
                }

                // merge and put merged files into temp dir
                string baseTmpDir = FileHelper.GetTempDirectoryName(tmpLettersDirectory);
                string tmpDir     = baseTmpDir + "EPC Letters" + @"\";
                Directory.CreateDirectory(tmpDir);
                string[] tmpFiles = new string[filesToPrintHash.Keys.Count];
                IDictionaryEnumerator enumerator = filesToPrintHash.GetEnumerator();
                for (int i = 0; enumerator.MoveNext(); i++)
                {
                    ArrayList files   = (ArrayList)enumerator.Value;
                    string    docName = (string)enumerator.Key;


                    // last file is screwing up, so just re-add the last file again for a temp fix
                    files.Add(files[files.Count - 1]);


                    Letter.FileContents fileContents = Letter.FileContents.Merge((Letter.FileContents[])files.ToArray(typeof(Letter.FileContents)), docName); // .pdf

                    string tmpFileName = tmpDir + fileContents.DocName;
                    System.IO.File.WriteAllBytes(tmpFileName, fileContents.Contents);
                    tmpFiles[i] = tmpFileName;
                }

                // zip em
                string zipFileName = "EPC Letters.zip";
                string zipFilePath = baseTmpDir + zipFileName;
                ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
                zip.CreateEmptyDirectories = true;
                zip.CreateZip(zipFilePath, tmpDir, true, "");

                // get filecontents of zip here
                Letter.FileContents zipFileContents = new Letter.FileContents(zipFilePath, zipFileName);
                Session["downloadFile_Contents"] = zipFileContents.Contents;
                Session["downloadFile_DocName"]  = zipFileContents.DocName;

                // delete files
                for (int i = 0; i < tmpFiles.Length; i++)
                {
                    System.IO.File.SetAttributes(tmpFiles[i], FileAttributes.Normal);
                    System.IO.File.Delete(tmpFiles[i]);
                }
                System.IO.File.SetAttributes(zipFilePath, FileAttributes.Normal);
                System.IO.File.Delete(zipFilePath);
                System.IO.Directory.Delete(tmpDir, false);
                System.IO.Directory.Delete(baseTmpDir, false);

                // put in session variables so when it reloads to this page, we can popup the download window
                Page.ClientScript.RegisterStartupScript(this.GetType(), "download", "<script language=javascript>window.open('DownloadFile.aspx','_blank','status=1,toolbar=0,menubar=0,location=1,scrollbars=1,resizable=1,width=30,height=30');</script>");
            }

            if (!zipSeperately && filesToPrint.Count > 0)
            {
                Letter.FileContents fileContents = Letter.FileContents.Merge((Letter.FileContents[])filesToPrint.ToArray(typeof(Letter.FileContents)), "Referral Letters.doc");  // .pdf
                Session["downloadFile_Contents"] = fileContents.Contents;
                Session["downloadFile_DocName"]  = fileContents.DocName;

                // put in session variables so when it reloads to this page, we can popup the download window
                Page.ClientScript.RegisterStartupScript(this.GetType(), "download", "<script language=javascript>window.open('DownloadFile.aspx','_blank','status=1,toolbar=0,menubar=0,location=1,scrollbars=1,resizable=1,width=30,height=30');</script>");
            }


            double restExecutionTime = (double)(Environment.TickCount - startTime) / 1000.0;

            if (debugMode)
            {
                if (!viewListOnly)
                {
                    lblInfo.Text = @"<table cellpadding=""0"">
                                    <tr><td><b>Send Method</b></td><td style=""width:10px;""></td><td>" + SelectedSendMethod.ToString() + @"</td><td style=""width:25px;""></td><td><b>Query Time</b></td><td style=""width:10px;""></td><td>" + queryExecutionTime + @" seconds</td></tr>
                                    <tr><td><b>Count</b></td><td style=""width:10px;""></td><td>" + bookingsWithSentLetters.Rows.Count + @"</td><td style=""width:25px;""></td><td><b>Runing Time</b></td><td style=""width:10px;""></td><td>" + restExecutionTime + @" seconds</td></tr>
                                 </table>";
                }

                string countShowing = bookingsWithSentLetters.Rows.Count > MaxSending ? bookingsWithSentLetters.Rows.Count + " showing to re-generate. <br /><font color=red>* You can not generate more than 175 at a time. Please narrow your search before printing.</font>" : bookingsWithSentLetters.Rows.Count.ToString();
                if (viewListOnly)
                {
                    lblInfo.Text = @"<table cellpadding=""0"">
                                    <tr><td valign=""top""><b>Count</b></td><td style=""width:10px;""></td><td>" + countShowing + @"</td></tr>
                                 </table>";
                }


                if (viewListOnly)
                {
                    lblList.Text = @"<table class=""table table-bordered table-striped table-grid table-grid-top-bottum-padding-thick auto_width block_center"" cellpadding=""4"" border=""1"">
                                        <tr>
                                            <th style=""white-space:nowrap;"">Send By</th>
                                            <th>Booking</th>
                                            <th>Generate</th>
                                            <th>Referrer</th>
                                            <th>Email</th>
                                            <th>Fax</th>
                                            <th>Patient</th>
                                        </tr>" +
                                   (debugOutput.Length == 0 ? "<tr><td colspan=\"7\">No Rows</td></tr>" : debugOutput) +
                                   "</table>";
                }
            }
        }
        catch (CustomMessageException cmEx)
        {
            SetErrorMessage(cmEx.Message);
        }
        catch (Exception ex)
        {
            SetErrorMessage("", ex.ToString());
        }
    }
示例#44
0
    protected void Run(bool viewListOnly)
    {
        try
        {
            if (SelectedSendMethod == SendMethod.None)
            {
                throw new CustomMessageException("Send method not selected");
            }


            int staffID = Session != null && Session["StaffID"] != null?Convert.ToInt32(Session["StaffID"]) : -1;

            int siteID = -1;

            if (!chkIncClinics.Checked && !chkIncAgedCare.Checked)
            {
                throw new CustomMessageException("Plese check to generate for Clinics and/or Aged Care");
            }
            else if (chkIncClinics.Checked && chkIncAgedCare.Checked)
            {
                siteID = -1;
            }
            else if (chkIncClinics.Checked)
            {
                foreach (Site s in SiteDB.GetAll())
                {
                    if (s.SiteType.ID == 1)
                    {
                        siteID = s.SiteID;
                    }
                }
            }
            else if (chkIncAgedCare.Checked)
            {
                foreach (Site s in SiteDB.GetAll())
                {
                    if (s.SiteType.ID == 2)
                    {
                        siteID = s.SiteID;
                    }
                }
            }



            /*
             * // if called by automated settings there will be no session setting for SiteID or StaffID
             * // but siteID is needed to know which letter template to use for generation
             * if (siteID == null)
             * {
             *  Site[] sites = SiteDB.GetAll();
             *  siteID = (sites.Length == 1) ? sites[0].SiteID : sites[sites.Length - 1].SiteID; // if one site, use that -- else choose last one since clinics site developed first and exists
             * }
             */


            string outputInfo;
            string outputList;

            Letter.FileContents fileContents = ReferrerEPCLettersSendingV2.Run(
                SelectedSendMethod == SendMethod.Email ? ReferrerEPCLettersSendingV2.SendMethod.Email_To_Referrer : ReferrerEPCLettersSendingV2.SendMethod.Batch,
                siteID,
                staffID,
                Convert.ToInt32(registerReferrerID.Value),
                chkIncBatching.Checked,
                chkIncUnsent.Checked,
                chkIncWithEmailOrFaxOnly.Checked,
                viewListOnly,
                chkShowFullList.Checked,
                out outputInfo,
                out outputList,
                btnViewList.ClientID
                );

            lblInfo.Text = outputInfo;
            lblList.Text = outputList;

            if (fileContents != null)
            {
                System.Web.HttpContext.Current.Session["downloadFile_Contents"] = fileContents.Contents;
                System.Web.HttpContext.Current.Session["downloadFile_DocName"]  = fileContents.DocName;

                // put in session variables so when it reloads to this page, we can popup the download window
                Page.ClientScript.RegisterStartupScript(this.GetType(), "download", "<script language=javascript>window.open('DownloadFile.aspx','_blank','status=1,toolbar=0,menubar=0,location=1,scrollbars=1,resizable=1,width=30,height=30');</script>");
            }
        }
        catch (CustomMessageException cmEx)
        {
            SetErrorMessage(cmEx.Message);
        }
        catch (Exception ex)
        {
            SetErrorMessage("", ex.ToString());
        }

        return;



        bool debugMode = true;


        //
        //  We can not send email all their patients in one email - will be too big with attachments and rejected by their mail provider
        //  So if via email - need to send one at a time
        //  Then if cuts out or times out, it has processed some so don't need to re-process those when it's run again
        //
        //  remember to process the emails first ... so if any interruptions/errors ... at least some will have been processed
        //



        try
        {
            string sendMethod = rdioSendType.SelectedValue;
            if (!viewListOnly && SelectedSendMethod == SendMethod.None)
            {
                throw new CustomMessageException("Send method not selected");
            }

            string tmpLettersDirectory = Letter.GetTempLettersDirectory();
            if (!Directory.Exists(tmpLettersDirectory))
            {
                throw new CustomMessageException("Temp letters directory doesn't exist");
            }


            string debugOutput = string.Empty;
            int    startTime   = Environment.TickCount;

            DataTable bookingsWithUnsetnLetters = BookingDB.GetBookingsWithEPCLetters(DateTime.MinValue, DateTime.MinValue, Convert.ToInt32(registerReferrerID.Value), -1, false, true, chkIncBatching.Checked, chkIncUnsent.Checked);

            double queryExecutionTime = (double)(Environment.TickCount - startTime) / 1000.0;
            startTime = Environment.TickCount;

            ArrayList filesToPrint = new ArrayList();

            int       c = 0;
            int       currentRegReferrerID       = -1;
            ArrayList bookingsForCurrentReferrer = new ArrayList();
            foreach (DataRow row in bookingsWithUnsetnLetters.Rows)
            {
                //c++; if (c % 15 != 1) continue;
                if (c > ReferrerEPCLettersSendingV2.MaxSending)
                {
                    continue;
                }
                Tuple <Booking, PatientReferrer, bool, string, HealthCard> rowData = LoadRow(row);
                Booking         booking     = rowData.Item1;
                PatientReferrer pr          = rowData.Item2;
                bool            refHasEmail = rowData.Item3;
                string          refEmail    = rowData.Item4;
                HealthCard      hc          = rowData.Item5;


                if (pr.RegisterReferrer.RegisterReferrerID != currentRegReferrerID)
                {
                    filesToPrint.AddRange(ProcessReferrersLetters(viewListOnly, bookingsForCurrentReferrer, ref debugOutput));
                    currentRegReferrerID       = pr.RegisterReferrer.RegisterReferrerID;
                    bookingsForCurrentReferrer = new ArrayList();
                }

                bookingsForCurrentReferrer.Add(rowData);
            }

            // process last group
            filesToPrint.AddRange(ProcessReferrersLetters(viewListOnly, bookingsForCurrentReferrer, ref debugOutput));



            bool zipSeperately = true;

            if (zipSeperately && filesToPrint.Count > 0)
            {
                // seperate into doc types because can only merge docs with docs of same template (ie docname)
                Hashtable filesToPrintHash = new Hashtable();
                for (int i = 0; i < filesToPrint.Count; i++)
                {
                    Letter.FileContents curFileContents = (Letter.FileContents)filesToPrint[i];
                    if (filesToPrintHash[curFileContents.DocName] == null)
                    {
                        filesToPrintHash[curFileContents.DocName] = new ArrayList();
                    }
                    ((ArrayList)filesToPrintHash[curFileContents.DocName]).Add(curFileContents);
                }

                // merge and put merged files into temp dir
                string baseTmpDir = FileHelper.GetTempDirectoryName(tmpLettersDirectory);
                string tmpDir     = baseTmpDir + "EPC Letters" + @"\";
                Directory.CreateDirectory(tmpDir);
                string[] tmpFiles = new string[filesToPrintHash.Keys.Count];
                IDictionaryEnumerator enumerator = filesToPrintHash.GetEnumerator();
                for (int i = 0; enumerator.MoveNext(); i++)
                {
                    ArrayList files   = (ArrayList)enumerator.Value;
                    string    docName = (string)enumerator.Key;


                    // last file is screwing up, so just re-add the last file again for a temp fix
                    files.Add(files[files.Count - 1]);


                    Letter.FileContents fileContents = Letter.FileContents.Merge((Letter.FileContents[])files.ToArray(typeof(Letter.FileContents)), docName); // .pdf

                    string tmpFileName = tmpDir + fileContents.DocName;
                    System.IO.File.WriteAllBytes(tmpFileName, fileContents.Contents);
                    tmpFiles[i] = tmpFileName;
                }

                // zip em
                string zipFileName = "EPC Letters.zip";
                string zipFilePath = baseTmpDir + zipFileName;
                ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
                zip.CreateEmptyDirectories = true;
                zip.CreateZip(zipFilePath, tmpDir, true, "");

                // get filecontents of zip here
                Letter.FileContents zipFileContents = new Letter.FileContents(zipFilePath, zipFileName);
                Session["downloadFile_Contents"] = zipFileContents.Contents;
                Session["downloadFile_DocName"]  = zipFileContents.DocName;

                // delete files
                for (int i = 0; i < tmpFiles.Length; i++)
                {
                    System.IO.File.SetAttributes(tmpFiles[i], FileAttributes.Normal);
                    System.IO.File.Delete(tmpFiles[i]);
                }
                System.IO.File.SetAttributes(zipFilePath, FileAttributes.Normal);
                System.IO.File.Delete(zipFilePath);
                System.IO.Directory.Delete(tmpDir, false);
                System.IO.Directory.Delete(baseTmpDir, false);

                // put in session variables so when it reloads to this page, we can popup the download window
                Page.ClientScript.RegisterStartupScript(this.GetType(), "download", "<script language=javascript>window.open('DownloadFile.aspx','_blank','status=1,toolbar=0,menubar=0,location=1,scrollbars=1,resizable=1,width=30,height=30');</script>");
            }

            if (!zipSeperately && filesToPrint.Count > 0)
            {
                Letter.FileContents fileContents = Letter.FileContents.Merge((Letter.FileContents[])filesToPrint.ToArray(typeof(Letter.FileContents)), "Referral Letters.doc"); // .pdf
                Session["downloadFile_Contents"] = fileContents.Contents;
                Session["downloadFile_DocName"]  = fileContents.DocName;

                // put in session variables so when it reloads to this page, we can popup the download window
                Page.ClientScript.RegisterStartupScript(this.GetType(), "download", "<script language=javascript>window.open('DownloadFile.aspx','_blank','status=1,toolbar=0,menubar=0,location=1,scrollbars=1,resizable=1,width=30,height=30');</script>");
            }


            if (!viewListOnly && Convert.ToInt32(registerReferrerID.Value) == -1 && chkIncBatching.Checked)
            {
                SetLastDateBatchSendTreatmentNotesAllReferrers(DateTime.Now);
            }


            double restExecutionTime = (double)(Environment.TickCount - startTime) / 1000.0;

            if (debugMode)
            {
                string countGenrated = bookingsWithUnsetnLetters.Rows.Count > ReferrerEPCLettersSendingV2.MaxSending ? ReferrerEPCLettersSendingV2.MaxSending + " of " + bookingsWithUnsetnLetters.Rows.Count + " generated" : bookingsWithUnsetnLetters.Rows.Count.ToString() + " generated";
                string countShowing  = bookingsWithUnsetnLetters.Rows.Count > ReferrerEPCLettersSendingV2.MaxSending ? ReferrerEPCLettersSendingV2.MaxSending + " of " + bookingsWithUnsetnLetters.Rows.Count + " showing to generate. <br />* If there are more than " + ReferrerEPCLettersSendingV2.MaxSending + ", the next " + ReferrerEPCLettersSendingV2.MaxSending + " will have to be generated seperately after this." : bookingsWithUnsetnLetters.Rows.Count.ToString();

                if (!viewListOnly)
                {
                    lblInfo.Text = @"<table cellpadding=""0"">
                                    <tr><td><b>Send Method</b></td><td style=""width:10px;""></td><td>" + SelectedSendMethod.ToString() + @"</td><td style=""width:25px;""></td><td><b>Query Time</b></td><td style=""width:10px;""></td><td>" + queryExecutionTime + @" seconds</td></tr>
                                    <tr><td><b>Count</b></td><td style=""width:10px;""></td><td>" + countGenrated + @"</td><td style=""width:25px;""></td><td><b>Runing Time</b></td><td style=""width:10px;""></td><td>" + restExecutionTime + @" seconds</td></tr>
                                 </table>" + "<br />";
                }

                if (viewListOnly)
                {
                    lblInfo.Text = @"<table cellpadding=""0"">
                                    <tr><td valign=""top""><b>Count</b></td><td style=""width:10px;""></td><td>" + countShowing + @"</td></tr>
                                 </table>" + "<br />";
                }

                if (viewListOnly)
                {
                    lblList.Text = @"<table class=""table table-bordered table-striped table-grid table-grid-top-bottum-padding-thick auto_width block_center"" border=""1"">
                                        <tr>
                                            <th>Send By</th>
                                            <th>Booking</th>
                                            <th>Generate</th>
                                            <th>Referrer</th>
                                            <th>Email</th>
                                            <th>Patient</th>
                                        </tr>" +
                                   (debugOutput.Length == 0 ? "<tr><td colspan=\"6\">No Rows</td></tr>" : debugOutput) +
                                   "</table>";
                }
            }
        }
        catch (CustomMessageException cmEx)
        {
            SetErrorMessage(cmEx.Message);
        }
        catch (Exception ex)
        {
            SetErrorMessage(ex.ToString());
        }
    }
    public static Letter.FileContents Run(SendMethod sendMethod, int siteID, int staffID, int registerReferrerID, bool incBatching, bool incUnsent, bool viewListOnly, bool viewFullList, out string outputInfo, out string outputList, string btnViewListClientID)
    {
        RndPageID = (new Random()).Next().ToString();

        bool debugMode = true;

        string tmpLettersDirectory = Letter.GetTempLettersDirectory();

        if (!Directory.Exists(tmpLettersDirectory))
        {
            throw new CustomMessageException("Temp letters directory doesn't exist");
        }


        int    startTime = 0;
        double queryExecutionTimeClinic = 0;
        double generateFilesToPrintExecutionTimeClinic = 0;
        double queryExecutionTimeAgedCare = 0;
        double generateFilesToPrintExecutionTimeAgedCare = 0;

        outputInfo = string.Empty;
        outputList = string.Empty;


        //
        //  We can not send email all their patients in one email - will be too big with attachments and rejected by their mail provider
        //  So if via email - need to send one at a time
        //  Then if cuts out or times out, it has processed some so don't need to re-process those when it's run again
        //
        //  remember to process the emails first ... so if any interruptions/errors ... at least some will have been processed
        //


        Site[] allSites    = SiteDB.GetAll();
        bool   runAllSites = siteID == -1;

        Site agedCareSite = null;
        Site clinicSite   = null;

        Site[] sitesToRun = runAllSites ? allSites : new Site[] { SiteDB.GetByID(siteID) };
        foreach (Site s in sitesToRun)
        {
            if (s.SiteType.ID == 1)
            {
                clinicSite = s;
            }
            else if (s.SiteType.ID == 2)
            {
                agedCareSite = s;
            }
        }


        ArrayList filesToPrintClinic   = new ArrayList();
        ArrayList filesToPrintAgedCare = new ArrayList();
        string    debugOutput          = string.Empty;
        int       numGenerated         = 0;

        DataTable bookingsWithUnsetnLettersClinic   = null;
        DataTable bookingsWithUnsetnLettersAgedCare = null;

        if (clinicSite != null)
        {
            startTime = Environment.TickCount;

            bookingsWithUnsetnLettersClinic = BookingDB.GetBookingsWithEPCLetters(DateTime.MinValue, DateTime.MinValue, registerReferrerID, -1, false, true, incBatching, incUnsent);

            queryExecutionTimeClinic = (double)(Environment.TickCount - startTime) / 1000.0;
            startTime = Environment.TickCount;


            int       currentRegReferrerID       = -1;
            ArrayList bookingsForCurrentReferrer = new ArrayList();
            foreach (DataRow row in bookingsWithUnsetnLettersClinic.Rows)
            {
                numGenerated++;

                //if (numGenerated % 15 != 1) continue;
                if ((!viewListOnly || !viewFullList) && (numGenerated > MaxSending))
                {
                    continue;
                }

                Tuple <Booking, PatientReferrer, bool, string, string, HealthCard> rowData = LoadClinicRow(row);
                Booking         booking     = rowData.Item1;
                PatientReferrer pr          = rowData.Item2;
                bool            refHasEmail = rowData.Item3;
                string          refEmail    = rowData.Item4;
                string          refFax      = rowData.Item5;
                HealthCard      hc          = rowData.Item6;


                //if (booking.Patient == null || (booking.Patient.PatientID != 31522 && booking.Patient.PatientID != 27654))
                //{
                //    numGenerated--;
                //    continue;
                //}



                if (pr.RegisterReferrer.RegisterReferrerID != currentRegReferrerID)
                {
                    filesToPrintClinic.AddRange(ProcessReferrersClinicLetters(sendMethod, viewListOnly, clinicSite, staffID, bookingsForCurrentReferrer, ref debugOutput, btnViewListClientID));
                    currentRegReferrerID       = pr.RegisterReferrer.RegisterReferrerID;
                    bookingsForCurrentReferrer = new ArrayList();
                }

                bookingsForCurrentReferrer.Add(rowData);
            }

            // process last group
            filesToPrintClinic.AddRange(ProcessReferrersClinicLetters(sendMethod, viewListOnly, clinicSite, staffID, bookingsForCurrentReferrer, ref debugOutput, btnViewListClientID));

            generateFilesToPrintExecutionTimeClinic = (double)(Environment.TickCount - startTime) / 1000.0;
        }
        if (agedCareSite != null)
        {
            startTime = Environment.TickCount;

            bookingsWithUnsetnLettersAgedCare = BookingPatientDB.GetBookingsPatientOfferingsWithEPCLetters(DateTime.MinValue, DateTime.MinValue, registerReferrerID, -1, false, true, incBatching, incUnsent);

            queryExecutionTimeAgedCare = (double)(Environment.TickCount - startTime) / 1000.0;
            startTime = Environment.TickCount;


            int       currentRegReferrerID       = -1;
            ArrayList bookingsForCurrentReferrer = new ArrayList();
            foreach (DataRow row in bookingsWithUnsetnLettersAgedCare.Rows)
            {
                numGenerated++;
                //if (numGenerated % 15 != 1) continue;
                if ((!viewListOnly || !viewFullList) && (numGenerated > MaxSending))
                {
                    continue;
                }
                Tuple <BookingPatient, Offering, PatientReferrer, bool, string, string, HealthCard> rowData = LoadAgedCareRow(row);
                BookingPatient  bp          = rowData.Item1;
                Offering        offering    = rowData.Item2;
                PatientReferrer pr          = rowData.Item3;
                bool            refHasEmail = rowData.Item4;
                string          refEmail    = rowData.Item5;
                string          refFax      = rowData.Item6;
                HealthCard      hc          = rowData.Item7;

                //if (bp.Booking.Patient == null || (bp.Booking.Patient.PatientID != 31522 && bp.Booking.Patient.PatientID != 27654))
                //{
                //    numGenerated--;
                //    continue;
                //}

                if (pr.RegisterReferrer.RegisterReferrerID != currentRegReferrerID)
                {
                    filesToPrintAgedCare.AddRange(ProcessReferrersAgedCareLetters(sendMethod, viewListOnly, agedCareSite, staffID, bookingsForCurrentReferrer, ref debugOutput, btnViewListClientID));
                    currentRegReferrerID       = pr.RegisterReferrer.RegisterReferrerID;
                    bookingsForCurrentReferrer = new ArrayList();
                }

                bookingsForCurrentReferrer.Add(rowData);
            }

            // process last group
            filesToPrintAgedCare.AddRange(ProcessReferrersAgedCareLetters(sendMethod, viewListOnly, agedCareSite, staffID, bookingsForCurrentReferrer, ref debugOutput, btnViewListClientID));

            generateFilesToPrintExecutionTimeAgedCare = (double)(Environment.TickCount - startTime) / 1000.0;
        }

        startTime = Environment.TickCount;


        bool zipSeperately = true;

        Letter.FileContents zipFileContents = null;

        if (zipSeperately && (filesToPrintClinic.Count + filesToPrintAgedCare.Count) > 0)
        {
            // if 2 sites exist in the system - change doc names to have "[AgedCare]" or "[Clinics]" before docname
            if (allSites.Length > 1)
            {
                for (int i = 0; i < filesToPrintClinic.Count; i++)
                {
                    ((Letter.FileContents)filesToPrintClinic[i]).DocName = "[Clinics] " + ((Letter.FileContents)filesToPrintClinic[i]).DocName;
                }
                for (int i = 0; i < filesToPrintAgedCare.Count; i++)
                {
                    ((Letter.FileContents)filesToPrintAgedCare[i]).DocName = "[AgedCare] " + ((Letter.FileContents)filesToPrintAgedCare[i]).DocName;
                }
            }

            ArrayList filesToPrint = new ArrayList();
            filesToPrint.AddRange(filesToPrintClinic);
            filesToPrint.AddRange(filesToPrintAgedCare);



            // seperate into doc types because can only merge docs with docs of same template (ie docname)
            Hashtable filesToPrintHash = new Hashtable();
            for (int i = 0; i < filesToPrint.Count; i++)
            {
                Letter.FileContents curFileContents = (Letter.FileContents)filesToPrint[i];
                if (filesToPrintHash[curFileContents.DocName] == null)
                {
                    filesToPrintHash[curFileContents.DocName] = new ArrayList();
                }
                ((ArrayList)filesToPrintHash[curFileContents.DocName]).Add(curFileContents);
            }

            // merge and put merged files into temp dir
            string baseTmpDir = FileHelper.GetTempDirectoryName(tmpLettersDirectory);
            string tmpDir     = baseTmpDir + "Referral Letters" + @"\";
            Directory.CreateDirectory(tmpDir);
            string[] tmpFiles = new string[filesToPrintHash.Keys.Count];
            IDictionaryEnumerator enumerator = filesToPrintHash.GetEnumerator();
            for (int i = 0; enumerator.MoveNext(); i++)
            {
                ArrayList files   = (ArrayList)enumerator.Value;
                string    docName = (string)enumerator.Key;


                // last file is screwing up, so just re-add the last file again for a temp fix
                files.Add(files[files.Count - 1]);


                Letter.FileContents fileContents = Letter.FileContents.Merge((Letter.FileContents[])files.ToArray(typeof(Letter.FileContents)), docName); // .pdf

                string tmpFileName = tmpDir + fileContents.DocName;
                System.IO.File.WriteAllBytes(tmpFileName, fileContents.Contents);
                tmpFiles[i] = tmpFileName;
            }

            // zip em
            string zipFileName = "Referral Letters.zip";
            string zipFilePath = baseTmpDir + zipFileName;
            ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
            zip.CreateEmptyDirectories = true;
            zip.CreateZip(zipFilePath, tmpDir, true, "");

            // get filecontents of zip here
            zipFileContents = new Letter.FileContents(zipFilePath, zipFileName);
            //Letter.FileContents zipFileContents = new Letter.FileContents(zipFilePath, zipFileName);
            //System.Web.HttpContext.Current.Session["downloadFile_Contents"] = zipFileContents.Contents;
            //System.Web.HttpContext.Current.Session["downloadFile_DocName"]  = zipFileContents.DocName;

            // delete files
            for (int i = 0; i < tmpFiles.Length; i++)
            {
                System.IO.File.SetAttributes(tmpFiles[i], FileAttributes.Normal);
                System.IO.File.Delete(tmpFiles[i]);
            }
            System.IO.File.SetAttributes(zipFilePath, FileAttributes.Normal);
            System.IO.File.Delete(zipFilePath);
            System.IO.Directory.Delete(tmpDir, false);
            System.IO.Directory.Delete(baseTmpDir, false);

            // put in session variables so when it reloads to this page, we can popup the download window
            //Page.ClientScript.RegisterStartupScript(this.GetType(), "download", "<script language=javascript>window.open('DownloadFile.aspx','_blank','status=1,toolbar=0,menubar=0,location=1,scrollbars=1,resizable=1,width=30,height=30');</script>");
        }

        if (!zipSeperately && (filesToPrintClinic.Count + filesToPrintAgedCare.Count) > 0)
        {
            ArrayList filesToPrint = new ArrayList();
            filesToPrint.AddRange(filesToPrintClinic);
            filesToPrint.AddRange(filesToPrintAgedCare);

            zipFileContents = Letter.FileContents.Merge((Letter.FileContents[])filesToPrint.ToArray(typeof(Letter.FileContents)), "Referral Letters.doc"); // .pdf
            //Letter.FileContents fileContents = Letter.FileContents.Merge((Letter.FileContents[])filesToPrint.ToArray(typeof(Letter.FileContents)), "Referral Letters.doc"); // .pdf
            //System.Web.HttpContext.Current.Session["downloadFile_Contents"] = fileContents.Contents;
            //System.Web.HttpContext.Current.Session["downloadFile_DocName"]  = fileContents.DocName;

            // put in session variables so when it reloads to this page, we can popup the download window
            //Page.ClientScript.RegisterStartupScript(this.GetType(), "download", "<script language=javascript>window.open('DownloadFile.aspx','_blank','status=1,toolbar=0,menubar=0,location=1,scrollbars=1,resizable=1,width=30,height=30');</script>");
        }


        if (!viewListOnly && registerReferrerID == -1 && incBatching)
        {
            SetLastDateBatchSendTreatmentNotesAllReferrers(DateTime.Now);
        }


        double restExecutionTime = (double)(Environment.TickCount - startTime) / 1000.0;

        if (debugMode)
        {
            int    total         = (bookingsWithUnsetnLettersClinic == null ? 0 : bookingsWithUnsetnLettersClinic.Rows.Count) + (bookingsWithUnsetnLettersAgedCare == null ? 0 : bookingsWithUnsetnLettersAgedCare.Rows.Count);
            string countGenrated = total > MaxSending ? MaxSending + " of " + total + " generated" : total.ToString() + " generated";
            string countShowing  = total > MaxSending ? MaxSending + " of " + total + " showing to generate. <br />* If there are more than " + MaxSending + ", the next " + MaxSending + " will have to be generated seperately after this." : total.ToString();
            if (total > MaxSending && viewFullList)
            {
                countShowing = total + " showing to generate. <br />* If there are more than " + MaxSending + ", only the first " + MaxSending + " will be generated and batches of " + MaxSending + " will have to be generated seperately after.";
            }

            string queryExecutionTimeText = string.Empty;
            if (agedCareSite == null && clinicSite == null)
            {
                queryExecutionTimeText = "0";
            }
            if (agedCareSite == null && clinicSite != null)
            {
                queryExecutionTimeText = queryExecutionTimeClinic.ToString();
            }
            if (agedCareSite != null && clinicSite == null)
            {
                queryExecutionTimeText = queryExecutionTimeAgedCare.ToString();
            }
            if (agedCareSite != null && clinicSite != null)
            {
                queryExecutionTimeText = "[Clinics: " + queryExecutionTimeClinic + "] [AgedCare: " + queryExecutionTimeAgedCare + "]";
            }

            string restExecutionTimeText = string.Empty;
            if (agedCareSite == null && clinicSite == null)
            {
                restExecutionTimeText = "0";
            }
            if (agedCareSite == null && clinicSite != null)
            {
                restExecutionTimeText = (generateFilesToPrintExecutionTimeClinic + restExecutionTime).ToString();
            }
            if (agedCareSite != null && clinicSite == null)
            {
                restExecutionTimeText = (generateFilesToPrintExecutionTimeAgedCare + restExecutionTime).ToString();
            }
            if (agedCareSite != null && clinicSite != null)
            {
                restExecutionTimeText = "[Clinics: " + generateFilesToPrintExecutionTimeClinic + "] [AgedCare: " + generateFilesToPrintExecutionTimeAgedCare + "] [Merging" + restExecutionTime + "]";
            }

            if (!viewListOnly)
            {
                outputInfo = @"<table cellpadding=""0"">
                                <tr><td><b>Send Method</b></td><td style=""width:10px;""></td><td>" + sendMethod.ToString() + @"</td><td style=""width:25px;""></td><td><b>Query Time</b></td><td style=""width:10px;""></td><td>" + queryExecutionTimeText + @" seconds</td></tr>
                                <tr><td><b>Count</b></td><td style=""width:10px;""></td><td>" + countGenrated + @"</td><td style=""width:25px;""></td><td><b>Runing Time</b></td><td style=""width:10px;""></td><td>" + restExecutionTimeText + @" seconds</td></tr>
                                </table>";
            }

            if (viewListOnly)
            {
                outputInfo = @"<table cellpadding=""0"">
                                <tr><td valign=""top""><b>Count</b></td><td style=""width:10px;""></td><td>" + countShowing + @"</td></tr>
                                </table>";
            }

            if (viewListOnly)
            {
                outputList = @"<table class=""table table-bordered table-striped table-grid table-grid-top-bottum-padding-thick auto_width block_center"" border=""1"">
                                    <tr>
                                        <th>Site</th>
                                        <th>Send By</th>
                                        <th>Booking</th>
                                        <th>Generate</th>
                                        <th>Referrer</th>
                                        <th>Email</th>
                                        <th>Fax</th>
                                        <th>Update Email/Fax</th>
                                        <th>Patient</th>
                                    </tr>" +
                             (debugOutput.Length == 0 ? "<tr><td colspan=\"6\">No Rows</td></tr>" : debugOutput) +
                             "</table>";
            }
        }

        return(zipFileContents);
    }