static int Main() { byte [] buf = new byte [1]; AsyncCallback ac = new AsyncCallback (async_callback); IAsyncResult ar; int sum0 = 0; FileStream s = new FileStream ("async_read.cs", FileMode.Open); s.Position = 0; sum0 = 0; while (s.Read (buf, 0, 1) == 1) sum0 += buf [0]; s.Position = 0; do { ar = s.BeginRead (buf, 0, 1, ac, buf); } while (s.EndRead (ar) == 1); sum -= buf [0]; Thread.Sleep (100); s.Close (); Console.WriteLine ("CSUM: " + sum + " " + sum0); if (sum != sum0) return 1; return 0; }
/// <summary> /// /// </summary> /// <param name="iResult"></param> private void ReadCompleted(IAsyncResult iResult) { try { if (_Stream.EndRead(iResult) == 16) { /** Leer JACK en e HW. En el Evento viene con lógica cambiada */ // Jack = HidJack((byte)(~_Buffer[1])); /** Leer PTT en el HW En el Evento viene con lógica cambiada */ Ptt = HidPtt((byte)(~_Buffer[1])); _Stream.BeginRead(_Buffer, 0, 16, new AsyncCallback(ReadCompleted), null); } else { _Logger.Error("HID Callback..."); } } catch (System.OperationCanceledException x) { _Logger.Warn("ReadCompleted OperationCanceledException " + x.Message); } catch (Exception x) { _Logger.Warn("ReadCompleted", x); // _Stream.BeginRead(_Buffer, 0, 16, new AsyncCallback(ReadCompleted), null); Error = true; } }
private void btn_fileStreamRead_Click(object sender, EventArgs e) { //prepare path to file string fullPath = ApplicationPath.PathTo("Files/MyFile.txt"); //preparing for read in async manner FileStream fs = new FileStream(fullPath, FileMode.Open); byte[] array = new byte[fs.Length]; var c = SynchronizationContext.Current; //we do operation in async manner so right here we will not get result.. IAsyncResult asyncResult = fs.BeginRead(array, 0, array.Length, (t) => { byte[] arrayData = t.AsyncState as byte[]; //emulate long reading.. Thread.Sleep(1200); c.Post(p => { rctxbx_data.Text = Encoding.UTF8.GetString(arrayData); } , null); fs.Close(); }, array); //here we always will wait async for operation to complete fs.EndRead(asyncResult); //so,you can put here any code you want.. //here also.... this.Text = "File reading started before this message"; }
/// <summary> /// Copies the specified source file to the specified destination file, overwriting if it exists. /// </summary> /// <param name="source">The source.</param> /// <param name="destination">The destination.</param> public static void Copy(string source, string destination) { var bufferLength = 4 * 1024 * 32; var readBuffer = new Byte[bufferLength]; var writeBuffer = new Byte[bufferLength]; var readSize = -1; IAsyncResult writeResult; IAsyncResult readResult; using (var sourceStream = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.None, 8, FileOptions.Asynchronous | FileOptions.SequentialScan)) using (var destinationStream = new FileStream(destination, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 8, FileOptions.Asynchronous | FileOptions.SequentialScan)) { destinationStream.SetLength(sourceStream.Length); readSize = sourceStream.Read(readBuffer, 0, readBuffer.Length); readBuffer = Interlocked.Exchange(ref writeBuffer, readBuffer); while (readSize > 0) { writeResult = destinationStream.BeginWrite(writeBuffer, 0, readSize, null, null); readResult = sourceStream.BeginRead(readBuffer, 0, readBuffer.Length, null, null); destinationStream.EndWrite(writeResult); readSize = sourceStream.EndRead(readResult); readBuffer = Interlocked.Exchange(ref writeBuffer, readBuffer); } sourceStream.Close(); destinationStream.Close(); } }
private static void AsyncReadOneFileCallBackAnonimus() { Byte[] data = new Byte[100]; Console.WriteLine("Основной поток ID = {0}", Thread.CurrentThread.ManagedThreadId); FileStream fs = new FileStream(@"../../Program.cs", FileMode.Open, FileAccess.Read, FileShare.Read, 1024, FileOptions.Asynchronous); fs.BeginRead(data, 0, data.Length, delegate(IAsyncResult ar) { Console.WriteLine("Чтение в потоке {0} закончено", Thread.CurrentThread.ManagedThreadId); Int32 bytesRead = fs.EndRead(ar); fs.Close(); Console.WriteLine("Количество считаных байт = {0}", bytesRead); Console.WriteLine(Encoding.UTF8.GetString(data).Remove(0, 1)); Console.ReadLine(); }, null); Console.ReadLine(); }
public AsyncCallBackReader(FileStream s, int size, AsyncBytesReadDel meth) { stream = s; data = new byte[size]; callbackMethod = meth; asRes = s.BeginRead(data, 0, size, ReadIsComplete, null); }
/// <summary> /// 共享文件夹方式上传文件 /// </summary> public Response ShareFolderUploadFile(string localFileName, string remoteFileName) { //获取远程服务器的路径 string remoteDir = Path.GetDirectoryName(remoteFileName); var result = ConnectShareFolder(remoteDir); if (!result.Success) { return(result); } //将本地文件复制到远程目录 //File.Copy(localFileName, remoteFileName, true); long totalSize = 0; byte[] buffer; using (FileStream fs = new FileStream(localFileName, FileMode.Open, FileAccess.Read)) { totalSize = fs.Length; if (totalSize > BUFFER_SIZE) { buffer = new byte[BUFFER_SIZE]; fs.BeginRead(buffer, 0, BUFFER_SIZE, AsyncCopyFile, fs); } } return(new Response { }); }
// Метод чтения текста из файла параллельным потоком выполнения - // вызывает ошибку при попытке вывода текста в текстбокс, // созданный в основном потоке выполнения private void BeginGetData(string filename) { //готовим массив для приема прочитанных данных byte[] data = null; //создаем поток для чтения FileStream fs = File.Open(filename, FileMode.Open); //создаем массив для чтения data = new byte[fs.Length]; //вызываем встроенный в класс FileStream async //метод ReadAsync по имени этого метода ясно, //что он асинхронный, значит, вызывать его //надо со спецификатором await fs.BeginRead(data, 0, (int)fs.Length, (result) => { FileStream fs1 = (FileStream)((IAsyncResult)result).AsyncState; try { Console.WriteLine(fs1.CanRead); fs1.EndRead(result); //преобразовываем прочитанные данные из байтового //массива в строку и отображаем в текстовом поле Result Console.WriteLine(System.Text.Encoding.UTF8.GetString(data)); textBox1.Text = System.Text.Encoding.UTF8.GetString(data); } catch (Exception) { throw; } finally { fs1.Dispose(); } }, fs); }
public USBError Start() { toStop = false; try { if (toRead) { // the buffer size must be greater than the packet size of the endpoint stream.BeginRead(base._data, base._start, 2048, new AsyncCallback(Performed), null); } else { if (base._start < base._end) { stream.BeginWrite(base._data, base._start, base._end - base._start, new AsyncCallback(Performed), null); } else { toStop = true; } } } catch (Exception ioexc) { this.Stop(); this.lastException = new Exception("Stream cannot start:", ioexc); return(USBError.FAIL); } return(USBError.SUCCESS); }
static void Main(string[] args) { FileStream stream = new FileStream("plik.txt", FileMode.Open); byte[] buffer = new byte[1024]; IAsyncResult result = stream.BeginRead(buffer, 0, buffer.Length, myAsyncCallback, new object[] { stream, buffer }); }
// Note: the implementation is intentionally limited to files with a maximum size of 1024 // for the sake of simplicity public Task <string> ReadFileContentAsync(string path, Encoding endcoding) { var stream = new FileStream(path, FileMode.Open, FileAccess.Read); var tcs = new TaskCompletionSource <string>(); var buffer = new byte[1024]; stream.BeginRead( buffer, 0, 1024, asyncResult => { try { var numberOfBytesRead = stream.EndRead(asyncResult); Array.Resize(ref buffer, numberOfBytesRead); var taskResult = endcoding.GetString(buffer); tcs.SetResult(taskResult); } catch (Exception exception) { tcs.SetException(exception); } }, null); var result = tcs.Task; return(result); }
/// <summary> /// Called when a device read is completed. /// </summary> /// <param name="asyncResult">The async result.</param> private void OnReadComplete(IAsyncResult asyncResult) { try { if (_deviceStream.EndRead(asyncResult) == 4 && _deviceBuffer[1] == 0) { TimeSpan timeSpan = DateTime.Now - _lastCodeTime; int keyCode = _deviceBuffer[2]; if (keyCode != _lastCode || timeSpan.Milliseconds > 250) { if (_remoteButtonHandler != null) { _remoteButtonHandler(Name, keyCode.ToString()); } _lastCodeTime = DateTime.Now; } _lastCode = keyCode; } _deviceStream.BeginRead(_deviceBuffer, 0, _deviceBuffer.Length, OnReadComplete, null); } catch (Exception) { } }
/// <summary> /// Start the IR Server plugin. /// </summary> public override void Start() { Guid guid = new Guid(); Win32.HidD_GetHidGuid(ref guid); string devicePath = FindDevice(guid); if (String.IsNullOrEmpty(devicePath)) { throw new InvalidOperationException("Device not found"); } SafeFileHandle deviceHandle = Win32.CreateFile(devicePath, FileAccess.Read, FileShare.Read, IntPtr.Zero, FileMode.Open, Win32.EFileAttributes.Overlapped, IntPtr.Zero); int lastError = Marshal.GetLastWin32Error(); if (deviceHandle.IsInvalid) { throw new Win32Exception(lastError, "Failed to open device"); } //_deviceWatcher.RegisterDeviceRemoval(deviceHandle); _deviceBuffer = new byte[255]; _deviceStream = new FileStream(deviceHandle, FileAccess.Read, _deviceBuffer.Length, true); _deviceStream.BeginRead(_deviceBuffer, 0, _deviceBuffer.Length, OnReadComplete, null); }
public static void NetToFile(FileStream file, int intx) { int start = intx * size_bmp; //start asynchronous read file.BeginRead(buffer, start, size_bmp, OnEndRead, file); }
static void Main(string[] args) { if (File.Exists(testFile)) { File.Delete(testFile); } using (FileStream stream = File.Create(testFile)) { string fileContent = "御史大夫圣诞节钢结构"; byte[] contentByte = Encoding.UTF8.GetBytes(fileContent); stream.Write(contentByte, 0, contentByte.Length); } //异步读取文件中的类容 using (FileStream stream = new FileStream(testFile, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, FileOptions.Asynchronous)) { byte[] data = new byte[bufferSize]; ReadFileClass rfc = new ReadFileClass(stream, data);// 将自定义类型对象实例作为参数 // 开始异步读取 stream.BeginRead(data, 0, data.Length, userCallback, rfc); //模拟其他操作 Thread.Sleep(3 * 1000); Console.WriteLine("主线程执行完毕"); } Console.ReadKey(); }
/// <summary> /// /// </summary> /// <param name="callback"></param> /// <returns></returns> public IAsyncResult BeginReadContent(AsyncCallback callback) { switch (RequestMethod) { case WebRequestMethod.DownloadFile: if (null != _requestState && _requestState.SourceStream.CanRead) { return(_requestState.SourceStream.BeginRead(_requestState.ByteBuffer, 0, _requestState.ByteBuffer.Length, callback, this)); } break; case WebRequestMethod.UploadFile: if (null != _sourceStream && _sourceStream.CanRead) { return(_sourceStream.BeginRead(_requestState.ByteBuffer, 0, _requestState.ByteBuffer.Length, callback, this)); } break; } return(new NullAsyncResult()); }
/// <summary> /// Demonstrates the use of the APM with files, through the FileStream class. /// This method performs asynchronous reads and writes to copy data from an input /// file to an output file. Reads and writes are interlaced, and proceed in chunks /// of 8KB at a time (displaying progress to the console). /// </summary> static void APMWithFiles() { //using (FileStream reader = new FileStream(SOURCE_FILE_NAME, FileMode.Open, FileAccess.Read, FileShare.Read, BUFFER_SIZE, true)) //using (Stream writer = new FileStream(TARGET_FILE_NAME, FileMode.Create, FileAccess.Write, FileShare.None, BUFFER_SIZE, true)) using (FileStream reader = File.OpenRead(SOURCE_FILE_NAME)) // DO NOT USE THIS API FOR ASYNC OPERATIONS !!! using (Stream writer = File.OpenWrite(TARGET_FILE_NAME)) // DO NOT USE THIS API FOR ASYNC OPERATIONS !!! { byte[] buffer1 = new byte[BUFFER_SIZE]; while (true) { IAsyncResult ar1 = reader.BeginRead(buffer1, 0, buffer1.Length, null, null); do { Console.Write("R"); } while (!ar1.IsCompleted); int bytesRead; if ((bytesRead = reader.EndRead(ar1)) == 0) { break; //No more data to read } IAsyncResult ar2 = writer.BeginWrite(buffer1, 0, bytesRead, null, null); do { Console.Write("W"); } while (!ar2.IsCompleted); } } }
/// <summary> /// 异步读取文件 /// </summary> /// <param name="callback">读取的数据回调</param> public void ReadAsync(Action <byte[]> callback) { if (!Exists) { throw new IOException("file is not exists"); } var fs = new FileStream(FullName, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true ); var data = new byte[fs.Length]; fs.BeginRead(data, 0, data.Length, (result) => { fs.EndRead(result); data = Decrypted(data); fs.Close(); fs.Dispose(); callback.Invoke(data); }, null); }
private async Task ReadLenghtBytesFromFileAsync(string filename, int length) { byte[] buffer = new byte[length]; var s = new FileStream(filename, FileMode.Open); //var ac = new AsyncCallback((r) => //{ // int count = s.EndRead(r); // Console.WriteLine($"count: {count}"); // Console.WriteLine($"data: {Encoding.Default.GetString(buffer)}"); // s.Close(); // s.Dispose(); //}); //s.BeginRead(buffer, 0, buffer.Length, ac, null); // OR await Task.Factory.FromAsync(s.BeginRead(buffer, 0, buffer.Length, null, null), (r) => s.EndRead(r)); s.Close(); s.Dispose(); tb.Text = Encoding.Default.GetString(buffer); }
public static void Patch(Byte[] bytes, string patchfp) { // Modified from http://www.smwiki.net/wiki/IPS_patching_code MemoryStream romstream = new MemoryStream(bytes, true); FileStream ipsstream = new FileStream(patchfp, FileMode.Open, FileAccess.Read, FileShare.Read); int lint = (int)ipsstream.Length; byte[] ipsbyte = new byte[ipsstream.Length]; byte[] rombyte = new byte[romstream.Length]; IAsyncResult romresult; IAsyncResult ipsresult = ipsstream.BeginRead(ipsbyte, 0, lint, null, null); ipsstream.EndRead(ipsresult); int ipson = 5; int totalrepeats = 0; int offset = 0; bool keepgoing = true; while (keepgoing == true) { offset = ipsbyte[ipson] * 0x10000 + ipsbyte[ipson + 1] * 0x100 + ipsbyte[ipson + 2]; ipson++; ipson++; ipson++; if (ipsbyte[ipson] * 256 + ipsbyte[ipson + 1] == 0) { ipson++; ipson++; totalrepeats = ipsbyte[ipson] * 256 + ipsbyte[ipson + 1]; ipson++; ipson++; byte[] repeatbyte = new byte[totalrepeats]; for (int ontime = 0; ontime < totalrepeats; ontime++) { repeatbyte[ontime] = ipsbyte[ipson]; } romstream.Seek(offset, SeekOrigin.Begin); romresult = romstream.BeginWrite(repeatbyte, 0, totalrepeats, null, null); romstream.EndWrite(romresult); ipson++; } else { totalrepeats = ipsbyte[ipson] * 256 + ipsbyte[ipson + 1]; ipson++; ipson++; romstream.Seek(offset, SeekOrigin.Begin); romresult = romstream.BeginWrite(ipsbyte, ipson, totalrepeats, null, null); romstream.EndWrite(romresult); ipson = ipson + totalrepeats; } if (ipsbyte[ipson] == 69 && ipsbyte[ipson + 1] == 79 && ipsbyte[ipson + 2] == 70) { keepgoing = false; } } romstream.Close(); ipsstream.Close(); }
// Begin an asynchronous read operation. public override IAsyncResult BeginRead (byte[] buffer, int offset, int numBytes, AsyncCallback userCallback, Object stateObject) { return(realStream.BeginRead (buffer, offset, numBytes, userCallback, stateObject)); }
protected override void Open() { string devicePath = FindDevice(_deviceClass); if (devicePath == null) { return; } if (LogVerbose) { MceRemoteReceiver.LogInfo("Using {0}", devicePath); } SafeFileHandle deviceHandle = CreateFile(devicePath, FileAccess.Read, FileShare.ReadWrite, 0, FileMode.Open, FileFlag.Overlapped, 0); if (deviceHandle.IsInvalid) { throw new Exception(string.Format("Failed to open remote ({0})", GetLastError())); } _deviceWatcher.RegisterDeviceRemoval(deviceHandle); // open a stream from the device and begin an asynchronous read _deviceStream = new FileStream(deviceHandle, FileAccess.Read, 128, true); _deviceStream.BeginRead(_deviceBuffer, 0, _deviceBuffer.Length, new AsyncCallback(OnReadComplete), null); }
//async read callback private void AsyncReadCallback(IAsyncResult asyncResult) { try { int bytesRead = mInputStream.EndRead(asyncResult); if (bytesRead > 0) { mBufferSize += bytesRead; Thread.Sleep(TimeSpan.FromMilliseconds(10)); mInputStream.BeginRead(mBuffer, mBufferSize, mBuffer.Length - mBufferSize, AsyncReadCallback, null); } else { if (mFinishCallback != null) { mFinishCallback(this); } mInputStream.Close(); } } catch (Exception e) { Debug.LogError("Error: " + e.Message); if (mErrorCallback != null) { mErrorCallback(mPath, e.Message); } } }
//async read file private void AsyncBeginReadFile(string path, OnLoadFinish finishCallback, OnError errorCallback) { mPath = path; mFinishCallback = finishCallback; mErrorCallback = errorCallback; try { mInputStream = new FileStream(path, FileMode.Open); mBuffer = new byte[mInputStream.Length]; mBufferSize = 0; mInputStream.BeginRead(mBuffer, mBufferSize, mBuffer.Length, AsyncReadCallback, null); } catch (Exception e) { if (mErrorCallback != null) { mErrorCallback(mPath, "Error: " + e.Message); } else { Debug.LogError("Error: " + e.Message); } } }
static int Main () { byte [] buf = new byte [1]; AsyncCallback ac = new AsyncCallback (async_callback); IAsyncResult ar; int sum0 = 0; int count0 = 0; FileStream s = new FileStream ("async_read.exe", FileMode.Open, FileAccess.Read); s.Position = 0; while (s.Read (buf, 0, 1) == 1) { sum0 += buf [0]; count0 ++; } s.Position = 0; do { buf = new byte [1]; ar = s.BeginRead (buf, 0, 1, ac, buf); } while (s.EndRead (ar) == 1); Thread.Sleep (100); s.Close (); count0 ++; // async_callback is invoked for the "finished reading" case too Console.WriteLine ("CSUM: " + sum + " " + sum0); Console.WriteLine ("Count: " + count + " " + count0); if (sum != sum0 || count != count0) return 1; return 0; }
static void Main(string[] args) { FileStream fs = File.Open("pliczek.txt", FileMode.OpenOrCreate); byte[] buffer = new byte[1024]; fs.BeginRead(buffer, 0, buffer.Length, funkcja, new object[] { fs, buffer }); }
private void AsyncAndAwait() { // 1. 디스크로부터 파일의 내용을 읽는 동기 방식의 Read 메서드는 명령어가 순차적으로 실행됬다. using (FileStream fs = new FileStream(Application.dataPath + "/BaseResources/duelShock.png", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { byte[] buf = new byte[fs.Length]; fs.Read(buf, 0, buf.Length); Texture2D texture = new Texture2D(1, 1); texture.LoadImage(buf); IMG_duelShock.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f)); } // 2. 비동기 버전의 BeginRead 메서드를 호출 했을 때는 Read 동작 이후의 코드를 별도로 분리해 Completed 같은 형식의 메서드에 담아 처리해야 하는 불편함이 있었다. FileStream fSteam = new FileStream(Application.dataPath + "/BaseResources/test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); FileState fState = new FileState(); fState.Buffer = new byte[fSteam.Length]; fState.fs = fSteam; fSteam.BeginRead(fState.Buffer, 0, fState.Buffer.Length, ReadCompleted, fState); // 2번의 코드를 잘 보면 1번의 코드에서 ReadCompleted만 추가 된 것을 볼 수 있다. // 혹시 이 작업을 컴파일러가 알아서 해줄 수 는 없는가? > async/await 예약어의 탄생 }
static void Main(string[] args) { AsyncCallback callBack = new AsyncCallback(readFileCallback); byte[] buffer = new byte[128]; //--------------waitAll----------------// FileStream fs = new FileStream("C:\\Users\\user\\Desktop\\me\\FlorekIO\\FlorekIO\\IO\\zad6\\file.txt", FileMode.Open, FileAccess.Read); fs.BeginRead(buffer, 0, buffer.Length, readFileCallback, new object[] { fs, buffer, waitHandles[0] }); fs = new FileStream("C:\\Users\\user\\Desktop\\me\\FlorekIO\\FlorekIO\\IO\\zad6\\file.txt", FileMode.Open, FileAccess.Read); fs.BeginRead(buffer, 0, buffer.Length, readFileCallback, new object[] { fs, buffer, waitHandles[1] }); WaitHandle.WaitAll(waitHandles); //-----------waitAny----------------// fs = new FileStream("C:\\Users\\user\\Desktop\\me\\FlorekIO\\FlorekIO\\IO\\zad6\\file.txt", FileMode.Open, FileAccess.Read); DateTime dt = DateTime.Now; fs.BeginRead(buffer, 0, buffer.Length, readFileCallback, new object[] { fs, buffer, waitHandles[0] }); fs = new FileStream("C:\\Users\\user\\Desktop\\me\\FlorekIO\\FlorekIO\\IO\\zad6\\file.txt", FileMode.Open, FileAccess.Read); fs.BeginRead(buffer, 0, buffer.Length, readFileCallback, new object[] { fs, buffer, waitHandles[1] }); int index = WaitHandle.WaitAny(waitHandles); Console.WriteLine("Task {0} finished first (time waited={1}).", index + 1, (DateTime.Now - dt).TotalMilliseconds); }
public void BeginReadThrowsForNegativeNumBytes() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write)) { Assert.Throws <ArgumentOutOfRangeException>("numBytes", () => fs.BeginRead(new byte[0], 0, -1, null, null)); } }
public void BeginReadThrowsForNullArray() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write)) { Assert.Throws <ArgumentNullException>("array", () => fs.BeginRead(null, 0, 0, null, null)); } }
/// <summary> /// Kicks off an asynchronous read which completes when data is read or when the device /// is disconnected. Uses a callback. /// </summary> private void BeginAsyncRead() { byte[] arrInputReport = new byte[m_nInputReportLength]; // put the buff we used to receive the stuff as the async state then we can get at it when the read completes m_oFile.BeginRead(arrInputReport, 0, m_nInputReportLength, new AsyncCallback(ReadCompleted), arrInputReport); }
static void zad2() { //ManualResetEvent manualEvent = new ManualResetEvent(false); FileStream f = new FileStream("TestFile.txt", FileMode.Open); byte[] a = new byte[1024]; IAsyncResult result = f.BeginRead(a, 0, a.Length, null, null); //dowolne operacje rownolegle do czytania for (int i = 0; i < 100; i++) { Console.Write(i + " "); } int size = f.EndRead(result); Console.WriteLine(Encoding.ASCII.GetString(a, 0, size)); //manualEvent.WaitOne(5000, false); }
public int Load(string filePath) { byte[] fileData; using (FileStream stream = new FileStream (filePath, FileMode.OpenOrCreate)) { fileData = new byte[stream.Length]; stream.BeginRead(fileData, 0, fileData.Length, new System.AsyncCallback(OnLoad), new FageFileState(++_countId, filePath, stream, fileData)); } return _countId; }
public bool runTest() { Console.WriteLine(s_strTFPath + "\\" + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; String strValue = String.Empty; try { FileStream fs2; String filName = s_strTFAbbrev + "TestFile.tmp"; if(File.Exists(filName)) File.Delete(filName); strLoc = "Loc_10000"; fs2 = new FileStream(filName, FileMode.Create); fs2.Close(); iCountTestcases++; if(fs2.CanRead) { iCountErrors++; printerr( "Error_1000a! CanRead returned true for closed stream"); } iCountTestcases++; if(fs2.CanWrite) { iCountErrors++; printerr( "Error_1000b! CanWrite returned true for closed stream"); } iCountTestcases++; if(fs2.CanSeek) { iCountErrors++; printerr( "Error_1000c! CanSeek returned true for closed stream"); } strLoc = "Loc_20000"; fs2 = new FileStream(filName, FileMode.Create); fs2.Close(); iCountTestcases++; try { Console.WriteLine(fs2.Length); iCountErrors++; printerr( "Error_2000a! Expected exception not thrown"); } catch (ObjectDisposedException iexc) { printinfo( "Info_2000b! Caught expected exception , iexc=="+iexc.Message); } catch (Exception exc) { iCountErrors++; printerr("Error_2000c! Incorrect exception thrown, exc=="+exc.ToString()); } iCountTestcases++; try { fs2.SetLength(5); iCountErrors++; printerr( "Error_2000d! Expected exception not thrown"); } catch (ObjectDisposedException iexc) { printinfo( "Info_2000e! Caught expected exception, iexc=="+iexc.Message); } catch ( Exception exc) { iCountErrors++; printerr( "Error_2000f! Incorrect exception thrown, exc=="+exc.ToString()); } iCountTestcases++; try { Console.WriteLine(fs2.Position); iCountErrors++; printerr("Error_2000g! Expected exception not thrown"); } catch (ObjectDisposedException iexc) { printinfo( "Info_2000h! Caught expected exception, iexc=="+iexc.Message); } catch (Exception exc) { iCountErrors++; printerr( "Error_2000i! Incorrect exception thrown, exc=="+exc.ToString()); } iCountTestcases++; try { fs2.Position = 1; iCountErrors++; printerr( "Error_2000j! Expected exception not thrown"); } catch ( ObjectDisposedException iexc) { printinfo( "Info_2000k! Caught expected exception, iexc=="+iexc.Message); } catch (Exception exc) { iCountErrors++; printerr( "Error_2000l! Incorrect exception thrown, exc=="+exc.ToString()); } iCountTestcases++; try { fs2.Write(new Byte[]{1}, 0, 1); iCountErrors++; printerr( "Error_2000m! Expected exception not thrown"); } catch (ObjectDisposedException iexc) { printinfo( "Info_2000n! Caught expected exception, iexc=="+iexc.Message); } catch (Exception exc) { iCountErrors++; printerr( "Error_2000o! Incorrect exception thrown, exc=="+exc.ToString()); } iCountTestcases++; try { fs2.Read(new Byte[1], 0, 1); iCountErrors++; printerr( "Error_2000p! Expected exception not thrown"); } catch (ObjectDisposedException iexc) { printinfo( "Info_2000q! Caught expected exception, iexc=="+iexc.Message); } catch (Exception exc) { iCountErrors++; printerr( "Error_2000r! Incorrect exception thrown, exc=="+exc.ToString()); } iCountTestcases++; try { fs2.EndWrite(fs2.BeginWrite(new Byte[]{1}, 0, 1, null, null)); iCountErrors++; printerr( "Error_2000s! Expected exception not thrown"); } catch (ObjectDisposedException iexc) { printinfo( "Info_2000t! Caught expected exception, iexc=="+iexc.Message); } catch (Exception exc) { iCountErrors++; printerr("Error_2000u! Incorrect exception thrown, exc=="+exc.ToString()); } iCountTestcases++; try { fs2.EndRead(fs2.BeginRead(new Byte[1], 0, 1, null, null)); iCountErrors++; printerr("Error_2000v! Expected exception not thrown"); } catch (ObjectDisposedException iexc) { printinfo( "Info_2000w! Caught expected exception, iexc=="+iexc.Message); } catch( Exception exc) { iCountErrors++; printerr( "Error_2000x! Incorrect exception thrown, exc=="+exc.ToString()); } iCountTestcases++; try { fs2.Flush(); iCountErrors++; printerr( "Error_2000y! Expected exception not thrwon"); } catch (ObjectDisposedException iexc) { printinfo( "Info_2000z! Caught expected exception, iexc=="+iexc.Message); } catch (Exception exc) { iCountErrors++; printerr( "Error_200aa! Incorrect exception thrown, exc=="+exc.ToString()); } iCountTestcases++; try { fs2.Lock(1,1); iCountErrors++; printerr( "Error_200ae! Expected exception not thrown"); } catch (ObjectDisposedException iexc) { printinfo( "Info_200af! Caught expected exception, iexc=="+iexc.Message); } catch (Exception exc) { iCountErrors++; printerr( "Error_200ag! Incorrect exception thrown, exc=="+exc.ToString()); } iCountTestcases++; try { fs2.ReadByte(); iCountErrors++; printerr( "Error_200ah! Expected exception not thrown"); } catch (ObjectDisposedException iexc) { printinfo( "Info_200ai! Caught expected exception, iexc=="+iexc.Message); } catch (Exception exc) { iCountErrors++; printerr( "Error_200aj! Incorrect exception thrown, exc=="+exc.ToString()); } iCountTestcases++; try { fs2.Seek(1, SeekOrigin.Begin); iCountErrors++; printerr( "Error_200ak! Expected exception not thrown"); } catch (ObjectDisposedException iexc) { printinfo( "Info_200al! Caught expected exception, iexc=="+iexc.Message); } catch (Exception exc) { iCountErrors++; printerr( "Error_200am! Incorrect exception thrown, exc=="+exc.ToString()); } iCountTestcases++; try { fs2.Unlock(1,1); iCountErrors++; printerr( "Error_200an! Expected exception not thrown"); } catch (ObjectDisposedException iexc) { printinfo( "Info_200ao! Caught expected exception, iexc=="+iexc.Message); } catch (Exception exc) { iCountErrors++; printerr( "Error_200ap! Incorrect exception thrown, exc=="+exc.ToString()); } strLoc = "Loc_40000"; iCountTestcases++; try { if(fs2.Handle.ToInt32() != -1) { iCountErrors++; printerr( "ERror_3000a! Incorrect value returned by GetHandle()=="+fs2.Handle); } } catch (ObjectDisposedException iexc) { printinfo( "Info_200ao! Caught expected exception, iexc=="+iexc.Message); } catch (Exception exc) { iCountErrors++; printerr( "Error_200ap! Incorrect exception thrown, exc=="+exc.ToString()); } if(File.Exists(filName)) File.Delete(filName); } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general=="+exc_general.ToString()); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+s_strTFName+" ,iCountTestcases=="+iCountTestcases.ToString()); return true; } else { Console.WriteLine("FAiL! "+s_strTFName+" ,iCountErrors=="+iCountErrors.ToString()+" , BugNums?: "+s_strActiveBugNums ); return false; } }
public bool runTest() { Console.WriteLine(s_strTFPath + "\\" + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); String strLoc = "Loc_000oo"; int iCountErrors = 0; int iCountTestcases = 0; try { String filName = s_strTFAbbrev+"TestFile"; Stream fs2; IAsyncResult iar; Int32 iReturn; Byte[] bArr; Byte[] bRead; if(File.Exists(filName)) File.Delete(filName); strLoc = "Loc_100aa"; iCountTestcases++; try { fs2 = new FileStream(null, FileMode.Create, FileAccess.Read, FileShare.None, 100, false); iCountErrors++; printerr( "Error_100bb! Expected exception not thrown"); fs2.Close(); } catch (ArgumentNullException aexc) { printinfo( "Info_100cc! Caught expected exception, aexc=="+aexc.Message); } catch (Exception exc) { iCountErrors++; printerr( "Error_100dd Incorrect exception thrown, exc=="+exc.ToString()); } strLoc = "Loc_300aa"; fs2 = new FileStream(filName, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 100, false); bArr = new Byte[1024*100]; for(int i = 0 ; i < bArr.Length ; i++) bArr[i] = (Byte)i; fs2.Write(bArr, 0, bArr.Length); fs2.Close(); bRead = new Byte[bArr.Length]; fs2 = new FileStream(filName, FileMode.Open); iar = fs2.BeginRead(bRead, 0, bRead.Length, null, null); iReturn = fs2.EndRead(iar); iCountTestcases++; if(!iar.IsCompleted) { iCountErrors++; printerr( " Error_300dd! Operation should be complete"); } iCountTestcases++; if(!iar.CompletedSynchronously) { iCountErrors++; printerr( "Error_300cc! Unexpectedly completed ASync"); } iCountTestcases++; if(iReturn != bArr.Length) { iCountErrors++; printerr( "Error_300bb! Expected=="+bArr.Length+", Return=="+iReturn); } for(int i = 0 ; i < bRead.Length ; i++) { iCountTestcases++; if(bRead[i] != bArr[i]) { printerr( "Error_300ff_"+i+"! Expected=="+bArr[i]+", got=="+bRead[i]); iCountErrors++; } } fs2.Close(); strLoc = "Loc_400aa"; fs2 = new FileStream(filName, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 100, true); bArr = new Byte[100*1024]; for(int i = 0 ; i < bArr.Length ; i++) bArr[i] = (Byte)i; fs2.Write(bArr, 0, bArr.Length); fs2.Close(); bRead = new Byte[bArr.Length]; fs2 = new FileStream(filName, FileMode.Open); iar = fs2.BeginRead(bRead, 0, bRead.Length, null, null); iReturn = fs2.EndRead(iar); iCountTestcases++; if(!iar.IsCompleted) { iCountErrors++; printerr( "Error_400bb! Operation should be complete"); } iCountTestcases++; if(!iar.CompletedSynchronously) { iCountErrors++; printerr( "Error_400cc! Unexpectedly completed Synchronously"); } iCountTestcases++; if(iReturn != bArr.Length) { iCountErrors++; printerr( "Error_400dd! Expected=="+bArr.Length+", Return=="+iReturn); } for(int i = 0 ; i < bRead.Length ; i++) { iCountTestcases++; if(bRead[i] != bArr[i]) { printerr( "Error_300ff_"+i+"! Expected=="+bArr[i]+", got=="+bRead[i]); iCountErrors++; } } fs2.Close(); if(File.Exists(filName)) File.Delete(filName); } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general=="+exc_general.ToString()); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+s_strTFName+" ,iCountTestcases=="+iCountTestcases.ToString()); return true; } else { Console.WriteLine("FAiL! "+s_strTFName+" ,iCountErrors=="+iCountErrors.ToString()); return false; } }
public bool runTest() { Console.WriteLine(s_strTFPath + "\\" + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); String strLoc = "Loc_000oo"; String strValue = String.Empty; try { FileStream fs2; Byte[] bArr, bResultArr; String fileName = s_strTFAbbrev+"TestFile.tmp"; AsyncCallback ascb; IAsyncResult iar; fs2 = new FileStream(fileName, FileMode.Create); bArr = new Byte[26]; for(int i = 0 ; i < 26 ; i++) bArr[i] = (Byte)((i%26)+65); fs2.Flush(); fs2.Close(); strLoc = "Loc_7882h"; fs2 = new FileStream(fileName, FileMode.Open); iCountTestcases++; try { fs2.BeginRead(null, 0, 0, null, null); iCountErrors++; printerr( "Error_18983! Expected exception not thrown"); } catch ( ArgumentNullException aexc) { printinfo( "Info_989su! Caught expected exception, aexc=="+aexc.Message); } catch (Exception exc) { iCountErrors++; printerr( "Error_9t898! Incorrect exception thrown, exc=="+exc.ToString()); } fs2.Close(); strLoc = "Loc_1298x"; for(int iLoop = 0 ; iLoop < iArrInvalidValues.Length ; iLoop++) { fs2 = new FileStream(fileName, FileMode.Open); iCountTestcases++; bArr = new Byte[]{0,1,2,3}; try { fs2.BeginRead(bArr, iArrInvalidValues[iLoop], 0, null, null); iCountErrors++; printerr("Error_298tk! Expected exception not thrown"); } catch (ArgumentOutOfRangeException aexc) { printinfo ( "Info_9888b! Caught expected exception, aexc=="+aexc.Message); } catch (Exception exc) { iCountErrors++; printerr( "Error_28g8b! Incorrect exception thrown, exc=="+exc.ToString()); } fs2.Close(); } strLoc = "Loc_77f8h"; for(int iLoop = 0 ; iLoop < iArrLargeValues.Length ; iLoop++) { fs2 = new FileStream(fileName, FileMode.Open); iCountTestcases++; bArr = new Byte[]{0,1,2,3}; try { fs2.BeginRead(bArr, iArrLargeValues[iLoop], 0, null, null); iCountErrors++; printerr( "Error_9t8g8! Expected exception not thrown"); } catch (ArgumentException aexc) { printinfo( "Info_t87gy! Caught expected exception, aexc=="+aexc.Message); } catch (Exception exc) { iCountErrors++; printerr( "Error_29y8g! Incorrect exception thrown, exc=="+exc.ToString()); } fs2.Close(); } strLoc = "Loc_89t8y"; for(int iLoop = 0 ; iLoop < iArrInvalidValues.Length ; iLoop++) { fs2 = new FileStream(fileName, FileMode.Open); iCountTestcases++; bArr = new Byte[]{0,1}; try { fs2.BeginRead(bArr, 0, iArrInvalidValues[iLoop], null, null); iCountErrors++; printerr( "Error_2868b! Expected exception not thrown"); } catch (ArgumentOutOfRangeException aexc) { printinfo( "Info_3388g! Caught expected exception, aexc=="+aexc.Message); } catch (Exception exc) { iCountErrors++; printerr( "Error_t958g! Incorrect exception thrown, exc=="+exc.ToString()); } fs2.Close(); } strLoc = "Loc_399il"; for(int iLoop = 0 ; iLoop < iArrLargeValues.Length ; iLoop++) { fs2 = new FileStream(fileName, FileMode.Open); iCountTestcases++; bArr = new Byte[]{0,1}; try { fs2.BeginRead(bArr, 0, iArrLargeValues[iLoop], null, null); iCountErrors++; printerr( "Error_5520j! Expected exception not thrown"); } catch (ArgumentException aexc) { printinfo( "Info_88tum! Caught expected exception, aexc=="+aexc.Message); } catch (Exception exc) { iCountErrors++; printerr( "Error_2090t! Incorrect exception thrown, exc=="+exc.ToString()); } fs2.Close(); } strLoc = "Loc_388hj"; fs2 = new FileStream(fileName, FileMode.Open); ascb = new AsyncCallback(this.CallBackMethod); bCallBackCalled = false; bArr = new Byte[]{0,1,2,3}; iar = fs2.BeginWrite(bArr, 0, 4, ascb, 5); fs2.EndWrite(iar); Thread.Sleep(1000); iCountTestcases++; if(!bCallBackCalled) { iCountErrors++; printerr( "Error_489xh! CallBackmethod not called"); } iCountTestcases++; if(!iar.IsCompleted) { iCountErrors++; printerr( "Error_29ycy! Completed not set correctly"); } iCountTestcases++; if(!iar.CompletedSynchronously) { iCountErrors++; printerr( "Error_8998c! Not done async"); } iCountTestcases++; if((Int32)iar.AsyncState != 5) { iCountErrors++; printerr( "Error_20hvb! Incorrect AsyncState"); } fs2.Position = 0; bResultArr = new Byte[8]; iar = fs2.BeginRead(bResultArr, 2, 3, ascb, 5); fs2.EndRead(iar); for(int i = 2 ; i < 5 ; i++) { iCountTestcases++; if(bResultArr[i] != i-2) { iCountErrors++; printerr( "Error_1888v! Expected=="+bArr[i-2]+", got=="+bResultArr[i]); } } fs2.Close(); IAsyncResult iar2; strLoc = "Loc_98y8b"; fs2 = new FileStream(fileName, FileMode.Create); ascb = new AsyncCallback(this.CallBackMethod); bCallBackCalled = false; bArr = new Byte[100000]; bResultArr = new Byte[bArr.Length]; for(int i = 0 ; i < bArr.Length ; i++) bArr[i] = (Byte)((i%26)+65); iar = fs2.BeginWrite(bArr, 0, bArr.Length, ascb, null); Console.WriteLine( bArr.Length ); fs2.EndWrite(iar); if(fs2.Length != bArr.Length) { iCountErrors++; printerr( "Error_98yxh! Incorrect number of chars written :: " + fs2.Length + " expected " + bArr.Length); } fs2.Position = 0; iar2 = fs2.BeginRead(bResultArr, 0, bResultArr.Length, null, null); Console.WriteLine( bArr.Length ); int iByteCount = fs2.EndRead(iar2) ; if( iByteCount != bResultArr.Length) { iCountErrors++; printerr( "Error_875y7! Incorrect number of chars read" + iByteCount); } for(int i = 0 ; i < bResultArr.Length ; i++) { if(bResultArr[i] != bArr[i]) { iCountErrors++; printerr( "Error_2439v! Expected=="+bArr[i]+" , got=="+bResultArr[i]); } } iCountTestcases++; if(!iar.CompletedSynchronously) { iCountErrors++; printerr( "Error_90ud9! Not done async"); } fs2.Close(); File.Delete(fileName); strLoc = "Loc_98yay"; fs2 = new FileStream(fileName, FileMode.Create); ascb = new AsyncCallback(this.CallBackMethod); bCallBackCalled = false; bArr = new Byte[2000]; bResultArr = new Byte[500]; for(int i = 0 ; i < bArr.Length ; i++) bArr[i] = (Byte)((i%26)+65); iar = fs2.BeginWrite(bArr, 104, 104, ascb, null); fs2.EndWrite( iar ); if(fs2.Length != 104) { iCountErrors++; printerr( "ERror_298yh! Incorrect number of bytes written"); } fs2.Position = 0; iar = fs2.BeginRead(bResultArr, 26, 104, null, null); if(fs2.EndRead(iar) != 104) { iCountErrors++; printerr( "ERror_49yxy! Incorrect number of byuytes read"); } for(int i = 26; i < 130 ; i++) { iCountTestcases++; if(bResultArr[i] != (Byte)((i%26)+65)) { iCountErrors++; printerr( "Error_298vc! value=="+bResultArr[i]); } } fs2.Close(); File.Delete(fileName); } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general=="+exc_general.ToString()); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+s_strTFName+" ,iCountTestcases=="+iCountTestcases.ToString()); return true; } else { Console.WriteLine("FAiL! "+s_strTFName+" ,iCountErrors=="+iCountErrors.ToString()+" , BugNums?: "+s_strActiveBugNums ); return false; } }
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) { bool bStartAsync = false; try { _log.Info("Starting process request..."); _log.Info("fontname: " + m_sFontName); string sNameToDecode; if (m_sFontName.Length > gc_sJsExtention.Length && gc_sJsExtention == m_sFontName.Substring(m_sFontName.Length - gc_sJsExtention.Length)) sNameToDecode = m_sFontName.Substring(0, m_sFontName.Length - gc_sJsExtention.Length); else sNameToDecode = m_sFontName; byte[] data_decode = Odtff_fonts.ZBase32Encoder.Decode(sNameToDecode); string sFontNameDecoded = System.Text.Encoding.UTF8.GetString(data_decode); _log.Info("fontnameDecoded: " + sFontNameDecoded); context.Response.Clear(); context.Response.Cache.SetExpires(DateTime.Now.AddMinutes(double.Parse(ConfigurationManager.AppSettings["resource.expires"], Constants.mc_oCultureInfo))); context.Response.Cache.SetSlidingExpiration(false); context.Response.Cache.SetCacheability(HttpCacheability.Public); context.Response.ContentType = Utils.GetMimeType(sFontNameDecoded); string contentDisposition = Utils.GetContentDisposition(context.Request.UserAgent, context.Request.Browser.Browser, context.Request.Browser.Version, m_sFontName); context.Response.AppendHeader("Content-Disposition", contentDisposition); string sRealFontName = sFontNameDecoded; if (gc_sJsExtention == Path.GetExtension(sRealFontName)) sRealFontName = sRealFontName.Substring(0, sRealFontName.Length - gc_sJsExtention.Length); string strFilepath; m_mapFontNameToFullPath.TryGetValue(sRealFontName.ToUpper(), out strFilepath); FileInfo oFileInfo = new FileInfo(strFilepath); if (oFileInfo.Exists) { DateTime oLastModified = oFileInfo.LastWriteTimeUtc; string sETag = oLastModified.Ticks.ToString("x"); DateTime oDateTimeUtcNow = DateTime.UtcNow; if (oLastModified.CompareTo(oDateTimeUtcNow) > 0) { _log.DebugFormat("LastModifiedTimeStamp changed from {0} to {1}", oLastModified, oDateTimeUtcNow); oLastModified = oDateTimeUtcNow; } string sRequestIfModifiedSince = context.Request.Headers["If-Modified-Since"]; string sRequestETag = context.Request.Headers["If-None-Match"]; bool bNoModify = false; if (false == string.IsNullOrEmpty(sRequestETag) || false == string.IsNullOrEmpty(sRequestIfModifiedSince)) { bool bRequestETag = true; if (false == string.IsNullOrEmpty(sRequestETag) && sRequestETag != sETag) bRequestETag = false; bool bRequestIfModifiedSince = true; if (false == string.IsNullOrEmpty(sRequestIfModifiedSince)) { try { DateTime oRequestIfModifiedSince = DateTime.ParseExact(sRequestIfModifiedSince, "R", System.Globalization.CultureInfo.InvariantCulture); if ((oRequestIfModifiedSince - oLastModified).TotalSeconds > 1) bRequestIfModifiedSince = false; } catch { bRequestIfModifiedSince = false; } } if (bRequestETag && bRequestIfModifiedSince) { context.Response.StatusCode = (int)HttpStatusCode.NotModified; bNoModify = true; } } if (false == bNoModify) { context.Response.Cache.SetETag(sETag); context.Response.Cache.SetLastModified(oLastModified.ToLocalTime()); FileStream oFileStreamInput = new FileStream(strFilepath, FileMode.Open, FileAccess.Read, FileShare.Read, (int)oFileInfo.Length, true); byte[] aBuffer = new byte[oFileStreamInput.Length]; TransportClass oTransportClass = new TransportClass(context, cb, oFileStreamInput, aBuffer, sFontNameDecoded); oFileStreamInput.BeginRead(aBuffer, 0, aBuffer.Length, ReadFileCallback, oTransportClass); bStartAsync = true; } } else context.Response.StatusCode = (int)HttpStatusCode.BadRequest; } catch(Exception e) { context.Response.StatusCode = (int)HttpStatusCode.BadRequest; _log.Error(context.Request.QueryString.ToString()); _log.Error("Exeption catched in BeginProcessRequest:", e); } TransportClass oTempTransportClass = new TransportClass(context, cb, null, null, null); if (false == bStartAsync) cb(new AsyncOperationData(oTempTransportClass)); return new AsyncOperationData(oTempTransportClass); }
public bool runTest() { Console.WriteLine(s_strTFPath + "\\" + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); String strLoc = "Loc_000oo"; String strValue = String.Empty; int iCountErrors = 0; int iCountTestcases = 0; try { String filName = s_strTFAbbrev+"TestFile"; Stream fs2; IAsyncResult iar; Byte[] bArr; if(File.Exists(filName)) File.Delete(filName); strLoc = "Loc_100aa"; fs2 = new FileStream(filName, FileMode.Create); iCountTestcases++; try { fs2.EndWrite(null); iCountErrors++; printerr( "Error_100bb! Expected exception not thrown"); } catch (ArgumentNullException aexc) { printinfo( "Info_100cc! Caught expected exception, aexc=="+aexc.Message); } catch (Exception exc) { iCountErrors++; printerr( "Error_100dd Incorrect exception thrown, exc=="+exc.ToString()); } fs2.Close(); strLoc = "Loc_200aa"; fs2 = new FileStream(filName, FileMode.Create); iar = fs2.BeginRead(new Byte[0], 0, 0, null, null); iCountTestcases++; try { fs2.EndWrite(iar); iCountErrors++; printerr( "Error_200bb! Expected exception not thrown"); } catch (ArgumentException aexc) { printinfo ("Info_200cc! Caught expected exception, aexc=="+aexc.Message); } catch (Exception exc) { iCountErrors++; printerr( "Error_200dd! Incorrect exception thrown, exc=="+exc.ToString()); } fs2.Close(); strLoc = "Loc_300aa"; fs2 = new FileStream(filName, FileMode.Create); bArr = new Byte[1024*1000]; for(int i = 0 ; i < bArr.Length ; i++) bArr[i] = (Byte)i; iar = fs2.BeginWrite(bArr, 0, bArr.Length, null, null); fs2.EndWrite(iar); iCountTestcases++; if(!iar.IsCompleted) { iCountErrors++; printerr( " Error_300dd! Operation should be complete"); } iCountTestcases++; iCountTestcases++; if(fs2.Length != bArr.Length) { iCountErrors++; printerr( "Error_300bb! Expected=="+bArr.Length+", Return=="+fs2.Length); } fs2.Close(); strLoc = "Loc_400aa"; fs2 = new FileStream(filName, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 100, true); bArr = new Byte[1000*1024]; for(int i = 0 ; i < bArr.Length ; i++) bArr[i] = (Byte)i; iar = fs2.BeginWrite(bArr, 0, bArr.Length, null, null); fs2.EndWrite(iar); iCountTestcases++; if(!iar.IsCompleted) { iCountErrors++; printerr( "Error_400bb! Operation should be complete"); } iCountTestcases++; iCountTestcases++; if(fs2.Length != bArr.Length) { iCountErrors++; printerr( "Error_400dd! Expected=="+bArr.Length+", Return=="+fs2.Length); } fs2.Close(); if(File.Exists(filName)) File.Delete(filName); } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general=="+exc_general.ToString()); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+s_strTFName+" ,iCountTestcases=="+iCountTestcases.ToString()); return true; } else { Console.WriteLine("FAiL! "+s_strTFName+" ,iCountErrors=="+iCountErrors.ToString()+" , BugNums?: "+s_strActiveBugNums ); return false; } }
public bool runTest() { Console.WriteLine(s_strTFPath + "\\" + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); int iCountTestcases = 0; String strLoc = "Loc_000oo"; String strValue = String.Empty; try { BinaryReader sr2; StreamWriter sw2; MemoryStream ms2; FileStream fs2; Byte[] bArrReturn; Byte[] bArr; String filName = s_strTFAbbrev+"Test.tmp"; if(File.Exists(filName)) File.Delete(filName); strLoc = "Loc_948yv"; ms2 = new MemoryStream(); sr2 = new BinaryReader(ms2); iCountTestcases++; for(int iLoop = 0 ; iLoop < iArrInvalidValues.Length ; iLoop++ ) { try { sr2.ReadBytes(iArrInvalidValues[iLoop]); iCountErrors++; printerr( "Error_1098g! Expected exception not thrown"); } catch (ArgumentOutOfRangeException aexc) { printinfo( "Info_7587b! Caught expected exception, exc=="+aexc.Message); } catch (Exception exc) { iCountErrors++; printerr( "Error_789gy! Incorrect exception thrown, exc=="+exc.ToString()); } } sr2.Close(); strLoc = "Loc_948yv"; ms2 = new MemoryStream(); sw2 = new StreamWriter(ms2); for(int i = 0 ; i < chArr.Length ; i++) sw2.Write(chArr[i]); sw2.Flush(); ms2.Position = 0; sr2 = new BinaryReader(ms2); iCountTestcases++; Byte[] bNewArray = null ; for(int iLoop = 0 ; iLoop < iArrLargeValues.Length ; iLoop++ ) { try { bNewArray = sr2.ReadBytes(iArrLargeValues[iLoop]); Console.WriteLine("length..." + bNewArray.Length ); if(!( bNewArray.Length == 0 || bNewArray.Length == 31)) { iCountErrors++; printerr( "Error_5543! Unexpected bytes are read from the stream... Length:" + bNewArray.Length); } } catch (OutOfMemoryException aexc) { printinfo( "Info_7342! Caught expected exception, exc=="+aexc.Message); } catch (Exception exc) { iCountErrors++; printerr( "Error_0843! Incorrect exception thrown, exc=="+exc.ToString()); } } sr2.Close(); strLoc = "Loc_7t09b"; ms2 = new MemoryStream(); sr2 = new BinaryReader(ms2); iCountTestcases++; bArrReturn = sr2.ReadBytes(3); if(bArrReturn.Length != 0) { iCountErrors++; printerr( "Error_2098uv! Read from empty stream, read=="+bArrReturn.Length); } sr2.Close(); strLoc = "Loc_2698b"; try { ms2 = new MemoryStream(); sw2 = new StreamWriter(ms2); for(int i = 0 ; i < chArr.Length ; i++) sw2.Write(chArr[i]); sw2.Flush(); ms2.Position = 0; sr2 = new BinaryReader(ms2); bArr = ms2.ToArray(); bInputBytes = ms2.ToArray(); bArrReturn = sr2.ReadBytes(bArr.Length); iCountTestcases++; if(bArrReturn.Length != bArr.Length) { iCountErrors++; printerr( "Error_1900c! Incorrect number of chars read"); } for(int i = 0 ; i < bArr.Length ; i++) { iCountTestcases++; if(bArrReturn[i] != bArr[i]) { iCountErrors++; printerr( "Error_298vc_"+i+"! Expected=="+(Int32)bArr[i]+", got=="+(Int32)bArrReturn[i]); } } } catch (Exception exc) { iCountErrors++; printerr( "Error_298yg! Unexpected exception thrown, exc=="+exc.ToString()); } strLoc = "Loc_9848v"; try { fs2 = new FileStream(filName, FileMode.Create); sw2 = new StreamWriter(fs2); for(int i = 0 ; i < chArr.Length ; i++) sw2.Write(chArr[i]); sw2.Flush(); sw2.Close(); fs2 = new FileStream(filName, FileMode.Open); bArr = new Byte[(Int32)fs2.Length]; fs2.EndRead(fs2.BeginRead(bArr, 0, (Int32)fs2.Length, null, null)); fs2.Position = 0; sr2 = new BinaryReader(fs2); bArrReturn = sr2.ReadBytes(bArr.Length); iCountTestcases++; if(bArrReturn.Length != bArr.Length) { iCountErrors++; printerr( "Error_0901x! Incorrect number of chars read, length=="+bArr.Length); } for(int i = 0 ; i < bArr.Length ; i++) { iCountTestcases++; if(bArrReturn[i] != bArr[i]) { iCountErrors++; printerr( "Error_98yv8!_"+i+"! Expected=="+(Int32)bArr[i]+", got=="+(Int32)bArrReturn[i]); } } sr2.Close(); } catch (Exception exc) { iCountErrors++; printerr( "Error_698y7! Unexpected exception thrown, exc=="+exc.ToString()); } Byte[] bytes = BitConverter.GetBytes('\u00FC'); for(int i = 0 ; i < bytes.Length ; i++) Console.WriteLine(bytes[i]); strLoc = "Loc_958hb"; fs2 = new FileStream(filName, FileMode.Create); BinaryWriter bw2 = new BinaryWriter(fs2, Encoding.Unicode); bw2.Write("\u00FA\u00FB\u00FC\u00FD\uFFFE"); bw2.Close(); fs2 = new FileStream(filName, FileMode.Open); sr2 = new BinaryReader(fs2, Encoding.Unicode); sr2.BaseStream.Position = 1 ; iCountTestcases++; if(sr2.ReadChar() != (Char)0xFA ) { iCountErrors++; printerr( "Error_t8yc! Incorrect character read"); } if(sr2.ReadChar() != (Char)0xFB) { iCountErrors++; printerr("Error_8yb78! Incorrect character read"); } bArrReturn = sr2.ReadBytes(4); iCountTestcases++; if(bArrReturn.Length != 4) { iCountErrors++; printerr( "Error_tg777! Incorrect number of chars read"); } iCountTestcases++; if(bArrReturn[0] != 252) { iCountErrors++; printerr( "Error_9t8yv! Incorrect byte read=="+bArrReturn[0]); } iCountTestcases++; if(bArrReturn[1] != 0) { iCountErrors++; printerr( "Error_2098b! Incorrect byte read=="+bArrReturn[1]); } iCountTestcases++; if(bArrReturn[2] != 253) { iCountErrors++; printerr( "Error_0199x! Incorrect byte read=="+bArrReturn[2]); } iCountTestcases++; if(bArrReturn[3] != 0) { iCountErrors++; printerr( "Error! Incorrect byte read=="+bArrReturn[3]); } iCountTestcases++; Int32 tmp; if((tmp = sr2.Read()) != 0xFFFE) { iCountErrors++; printerr( "Error_928yb! Incorrect value read, tmp=="+tmp); } iCountTestcases++; if((tmp = sr2.Read()) != -1) { iCountErrors++; printerr( "Error_t8753! Incorrect position in stream, tmp=="+tmp); } sr2.Close(); strLoc = "Loc_7y8f8"; ms2 = new MemoryStream(); sr2 = new BinaryReader(ms2); iCountTestcases++; if(sr2.ReadBytes(1).Length != 0) { iCountErrors++; printerr( "Error_398yc! Incorrect number of bytes read"); } m_PortSetEvent.Reset(); Thread tcpListenerThread = new Thread(new ThreadStart(Co5640ReadBytes.StartListeningTcp)); tcpListenerThread.Start(); Console.WriteLine("Listening"); Thread.Sleep( 1000 ); m_PortSetEvent.WaitOne(); Teleport("127.0.0.1"); Thread.Sleep( 1000 ); strLoc = "Loc_9066"; chArr = new Char[Int32.MaxValue/2000]; ms2 = new MemoryStream(); sw2 = new StreamWriter(ms2); for(int i = 0 ; i < chArr.Length ; i++) sw2.Write(rand.Next(Char.MinValue, Char.MaxValue)); Console.WriteLine("Scenario started"); sw2.Flush(); ms2.Position = 0; sr2 = new BinaryReader(ms2); iCountTestcases++; for(int iLoop = 0 ; iLoop < iArrValidValues.Length ; iLoop++ ) { try { ms2.Position = 0 ; bNewArray = sr2.ReadBytes(iArrValidValues[iLoop]); if(bNewArray.Length !=iArrValidValues[iLoop]) { iCountErrors++; printerr( "Error_5543! Unexpected bytes are read from the stream... Length:" + bNewArray.Length); } } catch (OutOfMemoryException aexc) { printinfo( "Info_7342! Caught expected exception, exc=="+aexc.Message); } catch (Exception exc) { iCountErrors++; printerr( "Error_0843! Incorrect exception thrown, exc=="+exc.ToString()); } } sr2.Close(); if(File.Exists(filName)) File.Delete(filName); } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general=="+exc_general.ToString()); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+s_strTFName+" ,iCountTestcases=="+iCountTestcases.ToString()); return true; } else { Console.WriteLine("FAiL! "+s_strTFName+" ,iCountErrors=="+iCountErrors.ToString()+" , BugNums?: "+s_strActiveBugNums ); return false; } }
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) { bool bStartAsync = false; try { _log.Info("Starting process request..."); _log.Info("fontname: " + m_sFontName); context.Response.Clear(); context.Response.Cache.SetExpires(DateTime.Now); context.Response.Cache.SetCacheability(HttpCacheability.Public); context.Response.ContentType = Utils.GetMimeType(m_sFontName); if (context.Request.ServerVariables.Get("HTTP_USER_AGENT").Contains("MSIE")) context.Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + context.Server.UrlEncode(m_sFontName) + "\""); else context.Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + m_sFontName + "\""); string sConfigFontDir = ConfigurationManager.AppSettings["utils.common.fontdir"]; string strFilepath; if (null != sConfigFontDir && string.Empty != sConfigFontDir) strFilepath = Path.Combine(Environment.ExpandEnvironmentVariables(sConfigFontDir), m_sFontName); else m_mapFontNameToFullPath.TryGetValue(m_sFontName.ToUpper(), out strFilepath); if (".js" == Path.GetExtension(m_sFontName)) { string[] aFontExts = {".ttf", ".ttc", ".otf"}; for(int i = 0; i < aFontExts.Length; i++) { strFilepath = Path.ChangeExtension(strFilepath, aFontExts[i]); if (File.Exists(strFilepath)) break; } } FileInfo oFileInfo = new FileInfo(strFilepath); if (oFileInfo.Exists) { DateTime oLastModified = oFileInfo.LastWriteTimeUtc; string sETag = oLastModified.Ticks.ToString("x"); DateTime oDateTimeUtcNow = DateTime.UtcNow; if (oLastModified.CompareTo(oDateTimeUtcNow) > 0) { _log.DebugFormat("LastModifiedTimeStamp changed from {0} to {1}", oLastModified, oDateTimeUtcNow); oLastModified = oDateTimeUtcNow; } string sRequestIfModifiedSince = context.Request.Headers["If-Modified-Since"]; string sRequestETag = context.Request.Headers["If-None-Match"]; bool bNoModify = false; if (false == string.IsNullOrEmpty(sRequestETag) || false == string.IsNullOrEmpty(sRequestIfModifiedSince)) { bool bRequestETag = true; if (false == string.IsNullOrEmpty(sRequestETag) && sRequestETag != sETag) bRequestETag = false; bool bRequestIfModifiedSince = true; if (false == string.IsNullOrEmpty(sRequestIfModifiedSince)) { try { DateTime oRequestIfModifiedSince = DateTime.ParseExact(sRequestIfModifiedSince, "R", System.Globalization.CultureInfo.InvariantCulture); if ((oRequestIfModifiedSince - oLastModified).TotalSeconds > 1) bRequestIfModifiedSince = false; } catch { bRequestIfModifiedSince = false; } } if (bRequestETag && bRequestIfModifiedSince) { context.Response.StatusCode = (int)HttpStatusCode.NotModified; bNoModify = true; } } if (false == bNoModify) { context.Response.Cache.SetETag(sETag); context.Response.Cache.SetLastModified(oLastModified); FileStream oFileStreamInput = new FileStream(strFilepath, FileMode.Open, FileAccess.Read, FileShare.Read, (int)oFileInfo.Length, true); byte[] aBuffer = new byte[oFileStreamInput.Length]; TransportClass oTransportClass = new TransportClass(context, cb, oFileStreamInput, aBuffer); oFileStreamInput.BeginRead(aBuffer, 0, aBuffer.Length, ReadFileCallback, oTransportClass); bStartAsync = true; } } else context.Response.StatusCode = (int)HttpStatusCode.BadRequest; } catch(Exception e) { context.Response.StatusCode = (int)HttpStatusCode.BadRequest; _log.Error(context.Request.Params.ToString()); _log.Error("Exeption catched in BeginProcessRequest:", e); } TransportClass oTempTransportClass = new TransportClass(context, cb, null, null); if (false == bStartAsync) cb(new AsyncOperationData(oTempTransportClass)); return new AsyncOperationData(oTempTransportClass); }