public void UnpackFiles(string srcdir, List <IArchiveEntry> files, string dstdir) { try { Stream.Reopen(true); SetProgressMax?.Invoke(files.Count); foreach (IArchiveEntry entry in files) { SetProgressNext?.Invoke(); byte[] file = GetFile(entry, false); string path = System.IO.Path.Combine(dstdir, srcdir.Length > 2 ? entry.Path.RemoveFirst(srcdir.RemoveFirstSeparator()) : entry.Path); string dir = System.IO.Path.GetDirectoryName(path); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } File.WriteAllBytes(path, file); } SetProgress?.Invoke(0); Stream.Close(); } catch (Exception e) { MessageBox.Show($"{e.Message}\n{e.Source}\n{e.StackTrace}"); } }
public byte[] ReadFlash(Fel fel, byte[] fes, byte[] uboot, UInt32 address, UInt32 length, string what = "NAND") { var size = length; size = (size + Fel.sector_size - 1) / Fel.sector_size; size = size * Fel.sector_size; long maxProgress = (size / 65536), progress = 0; var r = fel.ReadFlash(address, length, delegate(Fel.CurrentAction action, string command) { switch (action) { case Fel.CurrentAction.ReadingMemory: SetStatus("Reading " + what); break; } progress++; SetProgress?.Invoke(Math.Min(progress, maxProgress), maxProgress); } ); return(r); }
public void AddFilesV3(List <string> files, string srcdir, string dstdir) { Stream.Reopen(false); SetProgressMax?.Invoke(files.Count); int cl = Settings.CompressionLevel; Stream.Seek(-280, SeekOrigin.End); long current_end = Stream.ReadInt64() ^ Key.KEY_1; foreach (string file in files) { SetProgressNext?.Invoke(); byte[] data = File.ReadAllBytes(file); int size = data.Length; byte[] compressed = Zlib.Compress(data, cl); if (compressed.Length < size) { data = compressed; } string path = (dstdir + file.RemoveFirst(srcdir).RemoveFirstSeparator()).RemoveFirstSeparator(); var entry = Files.Where(x => x.Path == path).ToList(); if (entry.Count > 0) { if (data.Length <= entry[0].CSize) { entry[0].Size = size; entry[0].CSize = data.Length; Stream.Seek(entry[0].Offset, SeekOrigin.Begin); Stream.WriteBytes(data); } else { entry[0].Size = size; entry[0].CSize = data.Length; entry[0].Offset = current_end; Stream.Seek(current_end, SeekOrigin.Begin); current_end += data.Length; Stream.WriteBytes(data); } } else { Files.Add(new ArchiveEntryV3() { Path = path, Size = size, CSize = data.Length, Offset = current_end }); Stream.Seek(current_end, SeekOrigin.Begin); current_end += data.Length; Stream.WriteBytes(data); } } SaveFileTable(current_end); SetProgress?.Invoke(0); LoadData?.Invoke(0); LoadData?.Invoke(1); }
public void WriteFlash(Fel fel, byte[] fes, byte[] uboot, UInt32 address, byte[] data, bool verify = true, string what = "NAND") { var size = data.LongLength; size = (size + Fel.sector_size - 1) / Fel.sector_size; size = size * Fel.sector_size; if (data.LongLength != size) { var newData = new byte[size]; Array.Copy(data, newData, data.Length); data = newData; } long maxProgress = (size / 65536) * (verify ? 2 : 1), progress = 0; // upload kernel through fel fel.WriteFlash(address, data, delegate(Fel.CurrentAction action, string command) { switch (action) { case Fel.CurrentAction.WritingMemory: SetStatus?.Invoke("Writing " + what); break; } progress++; SetProgress?.Invoke(Math.Min(progress, maxProgress), maxProgress); } ); if (verify) { var r = fel.ReadFlash((UInt32)Fel.kernel_base_f, (UInt32)data.LongLength, delegate(Fel.CurrentAction action, string command) { switch (action) { case Fel.CurrentAction.ReadingMemory: SetStatus("Reading " + what); break; } progress++; SetProgress?.Invoke(Math.Min(progress, maxProgress), maxProgress); } ); if (!data.SequenceEqual(r)) { throw new Exception("Verify failed for " + what); } } }
public List <byte[]> GetFiles(List <IArchiveEntry> files) { Stream.Reopen(true); SetProgressMax?.Invoke(files.Count); List <byte[]> fs = new List <byte[]>(); foreach (IArchiveEntry entry in files) { SetProgressNext?.Invoke(); fs.Add(GetFile(entry, false)); } SetProgress?.Invoke(0); Stream.Close(); return(fs); }
public void Memboot(byte[] fes, byte[] uboot, byte[] bootImage, Fel.WriteLineHandler writeLineHandler = null) { var fel = new Fel(); fel.WriteLine += WriteLine; fel.Fes1Bin = fes; fel.UBootBin = uboot; if (!fel.Open()) { throw new Exception("USB Device Not Found"); } var size = CalcKernelSize(bootImage); if (size > bootImage.Length || size > Fel.transfer_max_size) { throw new Exception($"Invalid boot image size: {size}"); } size = (size + Fel.sector_size - 1) / Fel.sector_size; size = size * Fel.sector_size; if (bootImage.Length != size) { var newK = new byte[size]; Array.Copy(bootImage, newK, bootImage.Length); bootImage = newK; } long maxProgress = size / 65536, progress = 0; // upload kernel through fel fel.WriteMemory(Fel.transfer_base_m, bootImage, delegate(Fel.CurrentAction action, string command) { switch (action) { case Fel.CurrentAction.WritingMemory: SetStatus?.Invoke("Uploading boot image"); break; } progress++; SetProgress?.Invoke(Math.Min(progress, maxProgress), maxProgress); } ); var bootCommand = string.Format("boota {0:x}", Fel.transfer_base_m); RunCommand(fel, bootCommand, true); }
public void SaveFileTableV3(long filetable = -1) { try { Stream.Reopen(false); long FileTableOffset = filetable; if (FileTableOffset == -1) { Stream.Seek(-280, SeekOrigin.End); FileTableOffset = Stream.ReadInt64() ^ Key.KEY_1; Stream.Cut(FileTableOffset); } Stream.Seek(FileTableOffset, SeekOrigin.Begin); SetProgressMax?.Invoke(Files.Count); int cl = Settings.CompressionLevel; foreach (IArchiveEntry entry in Files) { SetProgressNext?.Invoke(); byte[] data = entry.Write(cl); Stream.WriteInt32(data.Length ^ Key.KEY_1); Stream.WriteInt32(data.Length ^ Key.KEY_2); Stream.WriteBytes(data); } Stream.WriteInt32(Key.ASIG_1); Stream.WriteInt16(3); Stream.WriteInt16(2); Stream.WriteInt64(FileTableOffset ^ Key.KEY_1); Stream.WriteInt32(0); Stream.WriteBytes(Encoding.Default.GetBytes("Angelica File Package, Perfect World.")); Stream.WriteBytes(new byte[215]); Stream.WriteInt32(Key.ASIG_2); Stream.WriteInt32(0); Stream.WriteInt32(Files.Count); Stream.WriteInt16(3); Stream.WriteInt16(2); Stream.Seek(4, SeekOrigin.Begin); Stream.WriteInt64(Stream.GetLenght()); Stream.Close(); SetProgress?.Invoke(0); } catch (Exception e) { MessageBox.Show($"{e.Message}\n{e.Source}\n{e.StackTrace}"); } }
public void CompressFile(string source, string destination) { var inFs = new FileStream(source, FileMode.Open, FileAccess.Read); var outFs = new FileStream(destination, FileMode.CreateNew, FileAccess.Write); Stream zStream = new LZipStream(outFs, CompressionMode.Compress); byte[] buffer = new byte[BUFFER_SIZE]; SetProgressBounds?.Invoke(this, new ProgressBoundsEventArgs { Minimum = 0, Maximum = inFs.Length }); while (inFs.Position + BUFFER_SIZE <= inFs.Length) { SetProgress?.Invoke(this, new ProgressEventArgs { Value = inFs.Position }); inFs.Read(buffer, 0, buffer.Length); zStream.Write(buffer, 0, buffer.Length); } buffer = new byte[inFs.Length - inFs.Position]; SetProgressBounds?.Invoke(this, new ProgressBoundsEventArgs { Minimum = 0, Maximum = inFs.Length }); inFs.Read(buffer, 0, buffer.Length); zStream.Write(buffer, 0, buffer.Length); inFs.Close(); zStream.Close(); outFs.Dispose(); }
public void ReadFileTableV3() { Stream.Reopen(true); Stream.Seek(-8, SeekOrigin.End); int FilesCount = Stream.ReadInt32(); SetProgressMax?.Invoke(FilesCount); Stream.Seek(-280, SeekOrigin.End); long FileTableOffset = Stream.ReadInt64() ^ Key.KEY_1; Stream.Seek(FileTableOffset, SeekOrigin.Begin); BinaryReader TableStream = new BinaryReader(new MemoryStream(Stream.ReadBytes((int)(Stream.GetLenght() - FileTableOffset - 288)))); for (int i = 0; i < FilesCount; ++i) { SetProgressNext?.Invoke(); int EntrySize = TableStream.ReadInt32() ^ Key.KEY_1; TableStream.ReadInt32(); Files.Add(new ArchiveEntryV3(TableStream.ReadBytes(EntrySize))); } SetProgress?.Invoke(0); Stream.Close(); LoadData?.Invoke(0); }
protected virtual void OnSetProgress(object sender, int e) { SetProgress?.Invoke(sender, e); }
void CompressNextMachine() { SetProgress?.Invoke(this, new ProgressEventArgs { Value = _machinePosition }); if (_machinePosition >= _machines.Length) { SetMessage?.Invoke(this, new MessageEventArgs { Message = Localization.Finished }); WorkFinished?.Invoke(this, System.EventArgs.Empty); return; } Machine machine = _machines[_machinePosition]; SetMessage2?.Invoke(this, new MessageEventArgs { Message = machine.Name }); using var ctx = Context.Create(Settings.Settings.Current.DatabasePath); string machineName = machine.Name; Dictionary <string, MediaByMachine> mediasByMachine = ctx.MediasByMachines. Where(f => f.Machine.Id == machine.Id && f.Media.IsInRepo). ToDictionary(f => f.Name); if (mediasByMachine.Count > 0) { SetProgress2Bounds?.Invoke(this, new ProgressBoundsEventArgs { Minimum = 0, Maximum = mediasByMachine.Count }); if (machineName.EndsWith(".zip", StringComparison.InvariantCultureIgnoreCase)) { machineName = machineName.Substring(0, machineName.Length - 4); } string machinePath = Path.Combine(_outPath, machineName); if (!Directory.Exists(machinePath)) { Directory.CreateDirectory(machinePath); } long mediaPosition = 0; foreach (KeyValuePair <string, MediaByMachine> mediaByMachine in mediasByMachine) { string outputPath = Path.Combine(machinePath, mediaByMachine.Key); if (!outputPath.EndsWith(".aif", StringComparison.InvariantCultureIgnoreCase)) { outputPath += ".aif"; } SetProgress2?.Invoke(this, new ProgressEventArgs { Value = mediaPosition }); string repoPath = null; string md5Path = null; string sha1Path = null; string sha256Path = null; DbMedia media = mediaByMachine.Value.Media; if (media.Sha256 != null) { byte[] sha256Bytes = new byte[32]; string sha256 = media.Sha256; for (int i = 0; i < 32; i++) { if (sha256[i * 2] >= 0x30 && sha256[i * 2] <= 0x39) { sha256Bytes[i] = (byte)((sha256[i * 2] - 0x30) * 0x10); } else if (sha256[i * 2] >= 0x41 && sha256[i * 2] <= 0x46) { sha256Bytes[i] = (byte)((sha256[i * 2] - 0x37) * 0x10); } else if (sha256[i * 2] >= 0x61 && sha256[i * 2] <= 0x66) { sha256Bytes[i] = (byte)((sha256[i * 2] - 0x57) * 0x10); } if (sha256[(i * 2) + 1] >= 0x30 && sha256[(i * 2) + 1] <= 0x39) { sha256Bytes[i] += (byte)(sha256[(i * 2) + 1] - 0x30); } else if (sha256[(i * 2) + 1] >= 0x41 && sha256[(i * 2) + 1] <= 0x46) { sha256Bytes[i] += (byte)(sha256[(i * 2) + 1] - 0x37); } else if (sha256[(i * 2) + 1] >= 0x61 && sha256[(i * 2) + 1] <= 0x66) { sha256Bytes[i] += (byte)(sha256[(i * 2) + 1] - 0x57); } } string sha256B32 = Base32.ToBase32String(sha256Bytes); sha256Path = Path.Combine(Settings.Settings.Current.RepositoryPath, "aaru", "sha256", sha256B32[0].ToString(), sha256B32[1].ToString(), sha256B32[2].ToString(), sha256B32[3].ToString(), sha256B32[4].ToString(), sha256B32 + ".aif"); } if (media.Sha1 != null) { byte[] sha1Bytes = new byte[20]; string sha1 = media.Sha1; for (int i = 0; i < 20; i++) { if (sha1[i * 2] >= 0x30 && sha1[i * 2] <= 0x39) { sha1Bytes[i] = (byte)((sha1[i * 2] - 0x30) * 0x10); } else if (sha1[i * 2] >= 0x41 && sha1[i * 2] <= 0x46) { sha1Bytes[i] = (byte)((sha1[i * 2] - 0x37) * 0x10); } else if (sha1[i * 2] >= 0x61 && sha1[i * 2] <= 0x66) { sha1Bytes[i] = (byte)((sha1[i * 2] - 0x57) * 0x10); } if (sha1[(i * 2) + 1] >= 0x30 && sha1[(i * 2) + 1] <= 0x39) { sha1Bytes[i] += (byte)(sha1[(i * 2) + 1] - 0x30); } else if (sha1[(i * 2) + 1] >= 0x41 && sha1[(i * 2) + 1] <= 0x46) { sha1Bytes[i] += (byte)(sha1[(i * 2) + 1] - 0x37); } else if (sha1[(i * 2) + 1] >= 0x61 && sha1[(i * 2) + 1] <= 0x66) { sha1Bytes[i] += (byte)(sha1[(i * 2) + 1] - 0x57); } } string sha1B32 = Base32.ToBase32String(sha1Bytes); sha1Path = Path.Combine(Settings.Settings.Current.RepositoryPath, "aaru", "sha1", sha1B32[0].ToString(), sha1B32[1].ToString(), sha1B32[2].ToString(), sha1B32[3].ToString(), sha1B32[4].ToString(), sha1B32 + ".aif"); } if (media.Md5 != null) { byte[] md5Bytes = new byte[16]; string md5 = media.Md5; for (int i = 0; i < 16; i++) { if (md5[i * 2] >= 0x30 && md5[i * 2] <= 0x39) { md5Bytes[i] = (byte)((md5[i * 2] - 0x30) * 0x10); } else if (md5[i * 2] >= 0x41 && md5[i * 2] <= 0x46) { md5Bytes[i] = (byte)((md5[i * 2] - 0x37) * 0x10); } else if (md5[i * 2] >= 0x61 && md5[i * 2] <= 0x66) { md5Bytes[i] = (byte)((md5[i * 2] - 0x57) * 0x10); } if (md5[(i * 2) + 1] >= 0x30 && md5[(i * 2) + 1] <= 0x39) { md5Bytes[i] += (byte)(md5[(i * 2) + 1] - 0x30); } else if (md5[(i * 2) + 1] >= 0x41 && md5[(i * 2) + 1] <= 0x46) { md5Bytes[i] += (byte)(md5[(i * 2) + 1] - 0x37); } else if (md5[(i * 2) + 1] >= 0x61 && md5[(i * 2) + 1] <= 0x66) { md5Bytes[i] += (byte)(md5[(i * 2) + 1] - 0x57); } } string md5B32 = Base32.ToBase32String(md5Bytes); md5Path = Path.Combine(Settings.Settings.Current.RepositoryPath, "aaru", "md5", md5B32[0].ToString(), md5B32[1].ToString(), md5B32[2].ToString(), md5B32[3].ToString(), md5B32[4].ToString(), md5B32 + ".aif"); } if (File.Exists(sha256Path)) { repoPath = sha256Path; } else if (File.Exists(sha1Path)) { repoPath = sha1Path; } else if (File.Exists(md5Path)) { repoPath = md5Path; } if (repoPath == null) { throw new ArgumentException(string.Format(Localization.CannotFindHashInRepository, media.Sha256 ?? media.Sha1 ?? media.Md5)); } var inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read); var outFs = new FileStream(outputPath, FileMode.Create, FileAccess.Write); SetMessage3?.Invoke(this, new MessageEventArgs { Message = string.Format(Localization.Copying, Path.GetFileName(outputPath)) }); SetProgress3Bounds?.Invoke(this, new ProgressBoundsEventArgs { Minimum = 0, Maximum = inFs.Length }); byte[] buffer = new byte[BUFFER_SIZE]; while (inFs.Position + BUFFER_SIZE <= inFs.Length) { SetProgress3?.Invoke(this, new ProgressEventArgs { Value = inFs.Position }); inFs.Read(buffer, 0, buffer.Length); outFs.Write(buffer, 0, buffer.Length); } buffer = new byte[inFs.Length - inFs.Position]; SetProgress3?.Invoke(this, new ProgressEventArgs { Value = inFs.Position }); inFs.Read(buffer, 0, buffer.Length); outFs.Write(buffer, 0, buffer.Length); inFs.Close(); outFs.Close(); mediaPosition++; } } Dictionary <string, DiskByMachine> disksByMachine = ctx.DisksByMachines. Where(f => f.Machine.Id == machine.Id && f.Disk.IsInRepo). ToDictionary(f => f.Name); if (disksByMachine.Count > 0) { SetProgress2Bounds?.Invoke(this, new ProgressBoundsEventArgs { Minimum = 0, Maximum = disksByMachine.Count }); if (machineName.EndsWith(".zip", StringComparison.InvariantCultureIgnoreCase)) { machineName = machineName.Substring(0, machineName.Length - 4); } string machinePath = Path.Combine(_outPath, machineName); if (!Directory.Exists(machinePath)) { Directory.CreateDirectory(machinePath); } long diskPosition = 0; foreach (KeyValuePair <string, DiskByMachine> diskByMachine in disksByMachine) { string outputPath = Path.Combine(machinePath, diskByMachine.Key); if (!outputPath.EndsWith(".chd", StringComparison.InvariantCultureIgnoreCase)) { outputPath += ".chd"; } SetProgress2?.Invoke(this, new ProgressEventArgs { Value = diskPosition }); string repoPath = null; string md5Path = null; string sha1Path = null; DbDisk disk = diskByMachine.Value.Disk; if (disk.Sha1 != null) { byte[] sha1Bytes = new byte[20]; string sha1 = disk.Sha1; for (int i = 0; i < 20; i++) { if (sha1[i * 2] >= 0x30 && sha1[i * 2] <= 0x39) { sha1Bytes[i] = (byte)((sha1[i * 2] - 0x30) * 0x10); } else if (sha1[i * 2] >= 0x41 && sha1[i * 2] <= 0x46) { sha1Bytes[i] = (byte)((sha1[i * 2] - 0x37) * 0x10); } else if (sha1[i * 2] >= 0x61 && sha1[i * 2] <= 0x66) { sha1Bytes[i] = (byte)((sha1[i * 2] - 0x57) * 0x10); } if (sha1[(i * 2) + 1] >= 0x30 && sha1[(i * 2) + 1] <= 0x39) { sha1Bytes[i] += (byte)(sha1[(i * 2) + 1] - 0x30); } else if (sha1[(i * 2) + 1] >= 0x41 && sha1[(i * 2) + 1] <= 0x46) { sha1Bytes[i] += (byte)(sha1[(i * 2) + 1] - 0x37); } else if (sha1[(i * 2) + 1] >= 0x61 && sha1[(i * 2) + 1] <= 0x66) { sha1Bytes[i] += (byte)(sha1[(i * 2) + 1] - 0x57); } } string sha1B32 = Base32.ToBase32String(sha1Bytes); sha1Path = Path.Combine(Settings.Settings.Current.RepositoryPath, "chd", "sha1", sha1B32[0].ToString(), sha1B32[1].ToString(), sha1B32[2].ToString(), sha1B32[3].ToString(), sha1B32[4].ToString(), sha1B32 + ".chd"); } if (disk.Md5 != null) { byte[] md5Bytes = new byte[16]; string md5 = disk.Md5; for (int i = 0; i < 16; i++) { if (md5[i * 2] >= 0x30 && md5[i * 2] <= 0x39) { md5Bytes[i] = (byte)((md5[i * 2] - 0x30) * 0x10); } else if (md5[i * 2] >= 0x41 && md5[i * 2] <= 0x46) { md5Bytes[i] = (byte)((md5[i * 2] - 0x37) * 0x10); } else if (md5[i * 2] >= 0x61 && md5[i * 2] <= 0x66) { md5Bytes[i] = (byte)((md5[i * 2] - 0x57) * 0x10); } if (md5[(i * 2) + 1] >= 0x30 && md5[(i * 2) + 1] <= 0x39) { md5Bytes[i] += (byte)(md5[(i * 2) + 1] - 0x30); } else if (md5[(i * 2) + 1] >= 0x41 && md5[(i * 2) + 1] <= 0x46) { md5Bytes[i] += (byte)(md5[(i * 2) + 1] - 0x37); } else if (md5[(i * 2) + 1] >= 0x61 && md5[(i * 2) + 1] <= 0x66) { md5Bytes[i] += (byte)(md5[(i * 2) + 1] - 0x57); } } string md5B32 = Base32.ToBase32String(md5Bytes); md5Path = Path.Combine(Settings.Settings.Current.RepositoryPath, "chd", "md5", md5B32[0].ToString(), md5B32[1].ToString(), md5B32[2].ToString(), md5B32[3].ToString(), md5B32[4].ToString(), md5B32 + ".chd"); } if (File.Exists(sha1Path)) { repoPath = sha1Path; } else if (File.Exists(md5Path)) { repoPath = md5Path; } if (repoPath == null) { throw new ArgumentException(string.Format(Localization.CannotFindHashInRepository, disk.Sha1 ?? disk.Md5)); } var inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read); var outFs = new FileStream(outputPath, FileMode.Create, FileAccess.Write); SetMessage3?.Invoke(this, new MessageEventArgs { Message = string.Format(Localization.Copying, Path.GetFileName(outputPath)) }); SetProgress3Bounds?.Invoke(this, new ProgressBoundsEventArgs { Minimum = 0, Maximum = inFs.Length }); byte[] buffer = new byte[BUFFER_SIZE]; while (inFs.Position + BUFFER_SIZE <= inFs.Length) { SetProgress3?.Invoke(this, new ProgressEventArgs { Value = inFs.Position }); inFs.Read(buffer, 0, buffer.Length); outFs.Write(buffer, 0, buffer.Length); } buffer = new byte[inFs.Length - inFs.Position]; SetProgress3?.Invoke(this, new ProgressEventArgs { Value = inFs.Position }); inFs.Read(buffer, 0, buffer.Length); outFs.Write(buffer, 0, buffer.Length); inFs.Close(); outFs.Close(); diskPosition++; } } _filesByMachine = ctx.FilesByMachines.Where(f => f.Machine.Id == machine.Id && f.File.IsInRepo). ToDictionary(f => f.Name); if (_filesByMachine.Count == 0) { _machinePosition++; Task.Run(CompressNextMachine); return; } SetProgress2Bounds?.Invoke(this, new ProgressBoundsEventArgs { Minimum = 0, Maximum = _filesByMachine.Count }); if (!machineName.EndsWith(".zip", StringComparison.InvariantCultureIgnoreCase)) { machineName += ".zip"; } var zf = new ZipFile(Path.Combine(_outPath, machineName), Encoding.UTF8) { CompressionLevel = CompressionLevel.BestCompression, CompressionMethod = CompressionMethod.Deflate, EmitTimesInUnixFormatWhenSaving = true, EmitTimesInWindowsFormatWhenSaving = true, UseZip64WhenSaving = Zip64Option.AsNecessary, SortEntriesBeforeSaving = true }; zf.SaveProgress += Zf_SaveProgress; foreach (KeyValuePair <string, FileByMachine> fileByMachine in _filesByMachine) { // Is a directory if ((fileByMachine.Key.EndsWith("/", StringComparison.InvariantCultureIgnoreCase) || fileByMachine.Key.EndsWith("\\", StringComparison.InvariantCultureIgnoreCase)) && fileByMachine.Value.File.Size == 0) { ZipEntry zd = zf.AddDirectoryByName(fileByMachine.Key.Replace('/', '\\')); zd.Attributes = FileAttributes.Normal; zd.CreationTime = DateTime.UtcNow; zd.AccessedTime = DateTime.UtcNow; zd.LastModified = DateTime.UtcNow; zd.ModifiedTime = DateTime.UtcNow; continue; } ZipEntry zi = zf.AddEntry(fileByMachine.Key, Zf_HandleOpen, Zf_HandleClose); zi.Attributes = FileAttributes.Normal; zi.CreationTime = DateTime.UtcNow; zi.AccessedTime = DateTime.UtcNow; zi.LastModified = DateTime.UtcNow; zi.ModifiedTime = DateTime.UtcNow; } zf.Save(); }
/// <summary> /// Сформировать sql файл с запросами. /// </summary> public void LoadIntoFile(string path) { double res = 0.0; int koksCol = ColumnKOKS.Rows.Count; // Число столбцов в таблице KOKS. string startReqLine = GetColumnsName(); // Получаем начальную строку для вставки данных. string valuesReqLine = String.Empty; // Строка для вставки с данными из Excel. string totalRequest = ""; // Общая строка запроса. //List<string> sqlRequests = new List<string>(); using (StreamWriter streamWriter = new StreamWriter(path, true, Encoding.UTF8)) { for (int i = 0; i < RowsCount; i++) // Должно быть RowsCount. { valuesReqLine = ""; for (int j = 1; j < koksCol; j++) { if (KoksInExcel.ContainsKey(ColumnKOKS.Rows[j][0].ToString())) { int index = KoksInExcel[ColumnKOKS.Rows[j][0].ToString()]; valuesReqLine += GetValueFromData(dataTable.Rows[i][index].ToString()) + ","; } else { valuesReqLine += "NULL,"; } } valuesReqLine = valuesReqLine.TrimEnd(','); valuesReqLine += ")"; totalRequest = startReqLine + valuesReqLine; try { //sqlRequests.Add(totalRequest); streamWriter.WriteLine(totalRequest); } catch (Exception ex) { MessageBox.Show("Ошибка при добавлении экземпляра:\n" + ex.Message, "Ошибка. Row " + i.ToString(), MessageBoxButton.OK, MessageBoxImage.Error); WriteMessage("Ошибка при добавлении экземпляра (строка №" + i.ToString() + "):\n" + ex.Message + "\n" + totalRequest); break; } finally { res += ProgressStep; if (SetProgress != null) { SetProgress.Invoke(res); } } } } if (SetProgress != null) { SetProgress.Invoke(0); } WriteMessage("Sql скрипт сформирован."); //using (SqlConnection connection = new SqlConnection(Connections.ConnectionStrings.SQLConnectionStirng)) //{ // connection.Open(); // SqlCommand command = connection.CreateCommand(); // for (int i = 0; i < RowsCount; i++) // Должно быть RowsCount. // { // valuesReqLine = ""; // for (int j = 1; j < koksCol; j++) // { // if (KoksInExcel.ContainsKey(ColumnKOKS.Rows[j][0].ToString())) // { // int index = KoksInExcel[ColumnKOKS.Rows[j][0].ToString()]; // valuesReqLine += GetValueFromData(dataTable.Rows[i][index].ToString()) + ","; // } // else // { // valuesReqLine += "NULL,"; // } // } // valuesReqLine = valuesReqLine.TrimEnd(','); // valuesReqLine += ")"; // totalRequest = startReqLine + valuesReqLine; // try // { // //command.CommandText = totalRequest; // sqlRequests.Add(totalRequest); // } // catch (Exception ex) // { // MessageBox.Show("Ошибка при добавлении экземпляра:\n" + ex.Message, "Ошибка. Row " + i.ToString(), MessageBoxButton.OK, MessageBoxImage.Error); // WriteMessage("Ошибка при добавлении экземпляра (строка №" + i.ToString() + "):\n" + ex.Message + "\n" + totalRequest); // break; // } // finally // { // res += ProgressStep; // if (SetProgress != null) { SetProgress.Invoke(res); } // } // } //} //if (SetProgress != null) { SetProgress.Invoke(0); } //WriteMessage("Данные из Excel-шаблона загружены в таблицу КОКС."); }
/// <summary> /// Загрузить данные в табилцу Кокс. /// </summary> public void LoadIntoKoks() { double res = 0.0; int koksCol = ColumnKOKS.Rows.Count; // Число столбцов в таблице KOKS. string startReqLine = GetColumnsName(); // Получаем начальную строку для вставки данных. string valuesReqLine = String.Empty; // Строка для вставки с данными из Excel. string totalRequest = ""; // Общая строка запроса. using (SqlConnection connection = new SqlConnection(Connections.ConnectionStrings.SQLConnectionStirng)) { connection.Open(); //SqlTransaction transaction = connection.BeginTransaction(); SqlCommand command = connection.CreateCommand(); //command.Transaction = transaction; for (int i = 0; i < RowsCount; i++) // Должно быть RowsCount. { valuesReqLine = ""; for (int j = 1; j < koksCol; j++) { if (KoksInExcel.ContainsKey(ColumnKOKS.Rows[j][0].ToString())) { int index = KoksInExcel[ColumnKOKS.Rows[j][0].ToString()]; valuesReqLine += GetValueFromData(dataTable.Rows[i][index].ToString()) + ","; } else { valuesReqLine += "NULL,"; } } valuesReqLine = valuesReqLine.TrimEnd(','); valuesReqLine += ")"; /*foreach (KeyValuePair<string,int> col in KoksInExcel) * { * string val = dataTable.Rows[i][col.Value].ToString(); * valuesReqLine += GetValueFromData(val) + ","; * } * * valuesReqLine = valuesReqLine.TrimEnd(',') + ")"; * * for (int j = 0; j < koksCol; j++) * { * * * string val = dataTable.Rows[i][ColumnKOKS.Rows[j][0].ToString()].ToString(); * if (j < koksCol - 1) * { * valuesReqLine += GetValueFromData(val) + ","; * } * else * { * valuesReqLine += GetValueFromData(val) + ")"; * } * }*/ totalRequest = startReqLine + valuesReqLine; //if (i == 6858) //{ // MessageBox.Show(totalRequest); //} try { command.CommandText = totalRequest; command.ExecuteNonQuery(); //transaction.Commit(); // Подтверждаем транзакцию. } catch (Exception ex) { //transaction.Rollback(); MessageBox.Show("Ошибка при добавлении экземпляра:\n" + ex.Message, "Ошибка. Row " + i.ToString(), MessageBoxButton.OK, MessageBoxImage.Error); WriteMessage("Ошибка при добавлении экземпляра (строка №" + i.ToString() + "):\n" + ex.Message + "\n" + totalRequest); break; } finally { res += ProgressStep; if (SetProgress != null) { SetProgress.Invoke(res); } } } } //MessageBox.Show("Загружено"); if (SetProgress != null) { SetProgress.Invoke(0); } WriteMessage("Данные из Excel-шаблона загружены в таблицу КОКС."); }