public ChunkedFileStream(string path, long fileSize, ChunksData chunksData, HashFunction hashFunction, WorkFlags workFlags = WorkFlags.None) { Checks.ArgumentNotNullOrEmpty(path, "path"); Checks.ArgumentMoreThanZero(fileSize, "fileSize"); Checks.ArgumentNotNull(hashFunction, "hashFunction"); DebugLogger.LogConstructor(); DebugLogger.LogVariable(path, "path"); DebugLogger.LogVariable(fileSize, "fileSize"); _fileSize = fileSize; _chunksData = chunksData; _hashFunction = hashFunction; _buffer = new byte[_chunksData.ChunkSize]; if ((workFlags | WorkFlags.PreservePreviousFile) != 0) { // Often you may want to continue downloading of a file if this exists // It tries to open a file and re-download it from the verified position. // It does not check the hash of the file. It trusts that the file is already valid up to that point. // Because the only way to download the file should be using Chunked Downloader. _fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); _fileStream.Seek(0, SeekOrigin.End); // seek and stay at the end, so we can append long currentFileSize = _fileStream.Position; // Let's make sure that file size is a multiply of chunk size. // If not, something is wrong with the file. if (currentFileSize % chunksData.ChunkSize == 0) { _chunkIndex = (int)(currentFileSize / chunksData.ChunkSize); } else { DebugLogger.LogWarningFormat( "File {0} size {1} is not a multiply of chunk size: {2}. Will recreate it.", path, currentFileSize, chunksData.ChunkSize); _fileStream.Close(); _fileStream.Dispose(); _fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None); } } else { _fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None); } }
public ChunkedFileStream([NotNull] string path, long fileSize, ChunksData chunksData, [NotNull] HashFunction hashFunction, WorkFlags workFlags = WorkFlags.None) { if (path == null) { throw new ArgumentNullException("path"); } if (fileSize <= 0) { throw new ArgumentOutOfRangeException("fileSize"); } if (hashFunction == null) { throw new ArgumentNullException("hashFunction"); } _logger = PatcherLogManager.DefaultLogger; _fileSize = fileSize; _chunksData = chunksData; _hashFunction = hashFunction; _buffer = new byte[_chunksData.ChunkSize]; _logger.LogTrace("path = " + path); _logger.LogTrace("fileSize = " + fileSize); _logger.LogTrace("chunksData.ChunkSize = " + chunksData.ChunkSize); bool preservePreviousFile = (workFlags | WorkFlags.PreservePreviousFile) != 0; _logger.LogTrace("preservePreviousFile = " + preservePreviousFile); if (preservePreviousFile) { // Often you may want to continue downloading of a file if this exists // It tries to open a file and re-download it from the verified position. // It does not check the hash of the file. It trusts that the file is already valid up to that point. // Because the only way to download the file should be using Chunked Downloader. _logger.LogDebug("Opening file stream..."); _fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); _fileStream.Seek(0, SeekOrigin.End); // seek and stay at the end, so we can append long currentFileSize = _fileStream.Position; _logger.LogDebug("File stream opened."); _logger.LogTrace("currentFileSize = " + currentFileSize); _logger.LogDebug("Checking whether stream can append to current file..."); if (currentFileSize == 0) { _logger.LogDebug("File is new. Append is not possible."); } // Let's make sure that file size is a multiply of chunk size. // If not, something is wrong with the file. else if (currentFileSize % chunksData.ChunkSize == 0) { _chunkIndex = (int)(currentFileSize / chunksData.ChunkSize); _logger.LogDebug(string.Format("Append is possible - starting from {0} chunk index.", _chunkIndex)); } else { _logger.LogDebug(string.Format( "File size {0} is not a multiply of chunk size: {1}. Append is not possible - recreating file.", currentFileSize, chunksData.ChunkSize)); _logger.LogDebug("Closing previous file stream..."); _fileStream.Close(); _fileStream.Dispose(); _logger.LogDebug("Previous file stream closed."); OpenNewFileStream(path); } } else { OpenNewFileStream(path); } }
// callback private void KeyGuardPacket_GetPacket(object sender, EventArgs e) { if (sender == hardWareConnect) { Telegram tg = hardWareConnect.InBuf.Dequeue(); // - разбор сообщений switch (tg.Cmd_T[0]) { case 0x90: // - ответ на команду switch (tg.Value[0]) { // - операция чтение case 0xE2: // - users if (tg.Ident[0] == 0x04) { byte[] fisNumCard = new byte[10]; // буфер под физ. номер карты пользователя Array.Copy(tg.Data, 30, fisNumCard, 0, fisNumCard.Length); Card newCard = new Card(BitConverter.ToUInt32(tg.Data, 0), BitConverter.ToUInt32(tg.Data, 4), BitConverter.ToUInt32(tg.Data, 16), BitConverter.ToUInt32(tg.Data, 20), BitConverter.ToUInt16(tg.Data, 28), BitConverter.ToUInt16(tg.Data, 40), fisNumCard); if (Cards.Find(x => x.Addr == newCard.Addr) == null) { Cards.Add(newCard); AddNewCardToComboBox(newCard.Addr); // запросим тексты Ф.И.О. someTelegram = new Telegram(0x91, 0x12, 0xE2, 4); Array.Copy(BitConverter.GetBytes(newCard.NameIndex), someTelegram.Data, 2); hardWareConnect.OutBuf.Enqueue(someTelegram); } } // - уровень доступа к ключам if (tg.Ident[0] == 0x10 && tg.Len == 0x68) { ushort[] timeZn = new ushort[16]; // - временная зона ushort[] dZlist = new ushort[16]; // - ключи for (int i = 0; i < 8; i++) { // - поищем пары: временная зона/ключи if (BitConverter.ToUInt16(tg.Data, 4 + i * 2) != 0 && BitConverter.ToUInt16(tg.Data, 4 + i * 2 + 16) != 0) { Array.Copy(tg.Data, 4 + i * 2, timeZn, i * 2, 2); Array.Copy(tg.Data, 4 + i * 2 + 16, dZlist, i * 2, 2); } } if (timeZn.Length > 0) //<- есть что-нибудь? { LevelToKeys newLKeys = new LevelToKeys(BitConverter.ToUInt32(tg.Data, 0), timeZn, dZlist); if (LKeys.Find(x => x.Addr == newLKeys.Addr) == null) { LKeys.Add(newLKeys); AddNewLevelToKeys(newLKeys.Addr); } } } // - Тексты if (tg.Ident[0] == 0x12 && tg.Len == 72) { Text newText = new Text(BitConverter.ToUInt32(tg.Data, 0)); if (Texts.Find(x => x.Addr == newText.Addr) == null) { for (int i = 0; i < 31; i++) { newText.TextBytes[i] = tg.Data[4 + i]; } Texts.Add(newText); GetDebugMess.Append(Encoding.ASCII.GetString(tg.Data, 4, tg.Len - 36 - 4)); } } // - заголовок if (tg.Ident[0] == 0xFE) { } break; // - операция запись case 0xE1: // - временная зона if (tg.Ident[0] == 0x06 && tg.Value[0] == 0xE1) { AddNewTimeZone(DateZones.Last().Addr); } // - Ключи(Key) if (tg.Ident[0] == 0x0F && tg.Value[0] == 0xE1) { //AddNewUnkKey(UnkKeys.Last().Addr); AddNewUnkKey(BitConverter.ToUInt32(tg.Data, 0)); } // - Уровень доступа к ключам if (tg.Ident[0] == 0x10 && tg.Value[0] == 0xE1) { AddNewLevelToKeys(LKeys.Last().Addr); } // - пользователи if (tg.Ident[0] == 0x04 && tg.Value[0] == 0xE1) { AddNewCardToComboBox(Cards.Last().Addr); } // - Тексты if (tg.Ident[0] == 0x12 && tg.Value[0] == 0xE1) { } break; // - форматирование case 0xEA: // - форматирование памяти if (tg.Ident[0] == 0xFF) { // - чтение заголовка //someTelegram = new Telegram(0x91, 0xFE, 0xE2, new byte[8] { 0x00, 0x00, 0x00, 0x01, 0x78, 0x56, 0x34, 0x12 }); //hardWareConnect.OutBuf.Enqueue(someTelegram); // - запрос состояния неизвестных ключей //someTelegram = new Telegram(0x82, 0x0F, 0xF3); //hardWareConnect.OutBuf.Enqueue(someTelegram); } break; } break; // - события от ключницы case 0x80: // - посмотрим какое событие пришло switch (tg.Ident[0]) { // - событие от ключей case 0x0F: // - ключ выдан if (tg.Value[0] == 0x32 || tg.Value[0] == 0x3B) //<- 3B - ?? почему-то приходит "Ключ выдан из другой ключницы" { if (UnkKeys.Find(x => x.Addr == BitConverter.ToUInt32(tg.Data, 0)) != null) { string key_name = Encoding.ASCII.GetString(UnkKeys.Find(x => x.Addr == BitConverter.ToUInt32(tg.Data, 0)).Name); string mess = "Ключ выдан - " + key_name; AddMessageBox(mess); } } // - ключ вернут if (tg.Value[0] == 0x72 || tg.Value[0] == 0x7B) //<- 7B - ?? почему-то приходит "Ключ вернут в другую ключницу" { if (UnkKeys.Find(x => x.Addr == BitConverter.ToUInt32(tg.Data, 0)) != null) { string key_name = Encoding.ASCII.GetString(UnkKeys.Find(x => x.Addr == BitConverter.ToUInt32(tg.Data, 0)).Name); string mess = "Ключ вернут - " + key_name; AddMessageBox(mess); } } break; // - системное время case 0x19: if (tg.Value[0] == 0xEC) { ClientFlags |= WorkFlags.isSendSystemTime; } break; } break; // - ответ на запросы состояния case 0x83: case 0x85: // - неизвестные ключи if (tg.Ident[0] == 0x0F && tg.Value[0] == 0x73) { if (tg.Len == 50) { Key newKey = new Key(addrKey++ /*BitConverter.ToUInt32(tg.Data, 0)*/, tg.Data[4], tg.Data[5], new byte[] { tg.Data[6], tg.Data[7], tg.Data[8], tg.Data[9], tg.Data[10], tg.Data[11], tg.Data[12], tg.Data[13] }); if (UnkKeys.Find(x => x.Addr == newKey.Addr) == null) { UnkKeys.Add(newKey); // - запишем данный ключ в БД someTelegram = new Telegram(0x91, 0x0F, 0xE1, newKey.GetBytesKey()); hardWareConnect.OutBuf.Enqueue(someTelegram); } } } break; // - проверка связи case 0xA3: if (tg.Ident[0] == 0xE5 && tg.Value[0] == 0x31) { // - запрос проверки связи //someTelegram = new Telegram(0xA2, 0xE5, 0x31); //hardWareConnect.OutBuf.Enqueue(someTelegram); if ((ClientFlags & WorkFlags.isSendstartCMD) == 0) { startCMD(); // - отправим начальные телеграммы ClientFlags |= WorkFlags.isSendstartCMD; } /*ClientFlags &= ~WorkFlags.isCheckConnection; * if ((ClientFlags & WorkFlags.isSendSystemTime) == 0) * { * // - системное время * someTelegram = new Telegram(0x81, 0x19, 0xEC, 4); * // - data = Time * someTelegram.Data = BitConverter.GetBytes(someTelegram.Time); * //OutBuf.Enqueue(someTelegram); * ClientFlags |= WorkFlags.isSendSystemTime;*/ /* * someTelegram = new Telegram(0x91); * someTelegram.Ident[0] = 0x05; * someTelegram.Value[0] = 0xE2; * someTelegram.Dst = dst; * dt = DateTime.Now; * tmp = (dt.Second & 0x3F) | ((dt.Minute & 0x3F) << 6) | ((dt.Hour & 0x1F) << 12) | ((dt.Day & 0x1F) << 17) | ((dt.Month & 0x0F) << 22) | (((dt.Year - 2010) & 0x3F) << 26); | someTelegram.Data = BitConverter.GetBytes(tmp); | someTelegram.Ref = reF; | OutBuf.Enqueue(someTelegram);}*/ } break; default: break; } } }