public int Save(string filePath, byte[] fileData) { using (FileStream stream = new FileStream (filePath, FileMode.OpenOrCreate)) { stream.BeginWrite(fileData, 0, fileData.Length, new System.AsyncCallback(OnSave), new FageFileState(++_countId, filePath, stream, fileData)); } return _countId; }
public static void WorkItemMethod(object mainEvent) { Console.WriteLine("\nStarting WorkItem.\n"); AutoResetEvent autoEvent = new AutoResetEvent(false); // Create some data. const int ArraySize = 10000; const int BufferSize = 1000; byte[] byteArray = new Byte[ArraySize]; new Random().NextBytes(byteArray); // Create two files and two State objects. FileStream fileWriter1 = new FileStream(@"C:\Test1@##.dat", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite, BufferSize, true); FileStream fileWriter2 = new FileStream(@"C:\Test2@##.dat", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite, BufferSize, true); State stateInfo1 = new State(fileWriter1, autoEvent); State stateInfo2 = new State(fileWriter2, autoEvent); // Asynchronously write to the files. fileWriter1.BeginWrite(byteArray, 0, byteArray.Length, new AsyncCallback(EndWriteCallback), stateInfo1); fileWriter2.BeginWrite(byteArray, 0, byteArray.Length, new AsyncCallback(EndWriteCallback), stateInfo2); // Wait for the callbacks to signal. autoEvent.WaitOne(); autoEvent.WaitOne(); fileWriter1.Close(); fileWriter2.Close(); Console.WriteLine("\nEnding WorkItem.\n"); // Signal Main that the work item is finished. ((AutoResetEvent)mainEvent).Set(); }
/// <summary> /// 添加文件方法 /// </summary> /// <param name="config"> 创建文件配置类</param> public void Create(IFileConfig config) { lock (_lockObject) { //得到创建文件配置类对象 var createFileConfig = config as CreateFileConfig; //检查创建文件配置类是否为空 if (this.CheckConfigIsError(config)) { return; } //假设创建完文件后写入一段话,实际项目中无需这么做,这里只是一个演示 char[] insertContent = "HellowWorld".ToCharArray(); //转化成 byte[] byte[] byteArrayContent = Encoding.Default.GetBytes(insertContent, 0, insertContent.Length); //根据传入的配置文件中来决定是否同步或异步实例化stream对象 FileStream stream = createFileConfig.IsAsync ? new FileStream(createFileConfig.CreateUrl, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 4096, true) : new FileStream(createFileConfig.CreateUrl, FileMode.Create); using (stream) { // 如果不注释下面代码会抛出异常,google上提示是WriteTimeout只支持网络流 // stream.WriteTimeout = READ_OR_WRITE_TIMEOUT; //如果该流是同步流并且可写 if (!stream.IsAsync && stream.CanWrite) { stream.Write(byteArrayContent, 0, byteArrayContent.Length); } else if (stream.CanWrite) //异步流并且可写 { stream.BeginWrite(byteArrayContent, 0, byteArrayContent.Length, this.End_CreateFileCallBack, stream); } stream.Close(); } } }
private void WriteLog(LogLevel level, string log) { var path = string.Format(@"{0}{1}\{2}", YFK.Core.Configuration.YFKConfig.Instance.WebSetting.LogPath, DateTime.Now.ToString("yyyy年MM月dd日"), level.ToString()); if (path.Contains(":\\") == false) { if (System.Web.HttpContext.Current != null) { path = System.Web.HttpContext.Current.Server.MapPath(path); } else { path = AppDomain.CurrentDomain.BaseDirectory + path; } } var fileName = string.Format("{0}.txt", DateTime.Now.ToString("HH")); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.Append, FileAccess.Write, FileShare.Write, 1024, FileOptions.Asynchronous)) { log = string.Format("================记录时间:{0}================\r\n{1}\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), log); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(log + "\r\n"); IAsyncResult writeResult = fs.BeginWrite(buffer, 0, buffer.Length, (asyncResult) => { var fStream = (FileStream)asyncResult.AsyncState; fStream.EndWrite(asyncResult); }, fs); fs.Close(); } }
public override void OnPostProcessRequest(ManosApp app, IHttpTransaction transaction, Action complete) { // LogFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"" combined // %h - Remote host -- DONT HAVE // %l - Remote log name -- DONT HAVE // %u - Remote user -- DONT HAVE // %t - Date+Time // %r - Request path // %s - Status Code // %b - Bytes sent // %Referer - // %User Agent - string line = String.Format("- - - [{0}] \"{1}\" {2} {3} - -\n", DateTime.Now.ToString("dd/MMM/yyyy:HH:mm:ss K"), transaction.Request.Path, transaction.Response.StatusCode, transaction.Response.Headers.ContentLength); byte [] data = Encoding.Default.GetBytes(line); stream.BeginWrite(data, 0, data.Length, null, null); complete(); }
public void Create(IFileConfig config) { lock (_lockObject) { CreateFileConfig fileConfig = config as CreateFileConfig; if (this.CheckConfigIsError(fileConfig)) { return; } char[] insertContent = "HelloWorld".ToCharArray(); byte[] byteArrayContent = Encoding.Default.GetBytes(insertContent, 0, insertContent.Length); FileStream fs = fileConfig.IsAsync ? new FileStream(fileConfig.CreateUrl, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 4096, true) : new FileStream(fileConfig.CreateUrl, FileMode.Create); using (fs) { // 如果不注释下面代码会抛出异常,google上提示是WriteTimeout只支持网络流 //fs.WriteTimeout = WriteTimeout; if (fs.CanWrite && !fs.IsAsync) { fs.Write(byteArrayContent, 0, byteArrayContent.Length); } else if (fs.CanWrite) { fs.BeginWrite(byteArrayContent, 0, byteArrayContent.Length, End_CreateFileCallBack, fs); } Console.WriteLine("正在以 {0} 的方式创建文件", fs.IsAsync ? "异步" : "同步"); fs.Close(); } } }
/// <summary> /// 根据配置需求,创建文件 /// </summary> /// <param name="config"></param> public static void Create(IFileConfig config) { lock (_lockObj) { CreateFileConfig createFileConfig = config as CreateFileConfig; if (createFileConfig == null) { return; } if (createFileConfig.CreateUrl == null) { return; } char[] insertContent = "HelloWorld".ToCharArray(); byte[] byteArrayContent = Encoding.Default.GetBytes(insertContent); FileStream stream = createFileConfig.IsAsync ? new FileStream(createFileConfig.CreateUrl, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, 4096, true) : new FileStream(createFileConfig.CreateUrl, FileMode.Create); using (stream) { if (stream.CanWrite) { if (!stream.IsAsync) { stream.Write(byteArrayContent, 0, byteArrayContent.Length); Console.WriteLine($"同步创建文件地址{stream.Name}"); } else { stream.BeginWrite(byteArrayContent, 0, byteArrayContent.Length, EndCreateFileCallBack, stream); } } } } }
public static AutoResetEvent ApmTest() { var buf = new byte[WRITE_DATA_SIZE]; new Random().NextBytes(buf); Console.WriteLine("Generated random data"); var evnt = new AutoResetEvent(false); var fStream = new FileStream("file1.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.None, WRITE_BLOCK_SIZE, FileOptions.WriteThrough); var sw = Stopwatch.StartNew(); fStream.BeginWrite(buf, 0, buf.Length, asyncResult => { var fs = (FileStream)asyncResult.AsyncState; fs.EndWrite(asyncResult); evnt.Set(); Console.WriteLine("Finished disk I/O! in {0} ms (thread {1})", sw.ElapsedMilliseconds, Thread.CurrentThread.ManagedThreadId); }, fStream); Console.WriteLine("Started disk I/O! in {0} ms total (thread {1})", sw.ElapsedMilliseconds, Thread.CurrentThread.ManagedThreadId); return(evnt); }
/// <summary> /// The main entry point for the application. /// </summary> public static void Test() { string guid = TunTapService.GetOneDeviceGuid(); TunTapService tunTapService = new TunTapService(guid); tunTapService.open(); Tap = tunTapService.tap; // return; object asyncReadState = new int(); readWait = new EventWaitHandle(false, EventResetMode.AutoReset); object asyncWriteState = new int(); writeWait = new EventWaitHandle(false, EventResetMode.AutoReset); AsyncCallback readCallback = new AsyncCallback(ReadCallback); AsyncCallback writeCallback = new AsyncCallback(WriteCallback); IAsyncResult res, res2; while (true) { Tap.BeginRead(buf, 0, buf.Length, readCallback, asyncReadState); readWait.WaitOne(); // // Reverse IPv4 addresses and send back to tun // //for (int i = 0; i < 4; ++i) //{ // byte tmp = buf[12 + i]; // buf[12 + i] = buf[16 + i]; // buf[16 + i] = tmp; //} Tap.BeginWrite(buf, 0, BytesRead, writeCallback, asyncWriteState); writeWait.WaitOne(); } }
public int ReceiveBuffer(int index, byte[] buffer) { _lastReceiveTime = DateTime.Now; if (ReceiveFilePartList[index]) { return(0); } else { lock (SyncLock) { ReceiveFilePartList[index] = true; _receivePartCount++; } FileStream.Position = index * _partSize; FileStream.BeginWrite( buffer, 0, buffer.Length, new AsyncCallback(EndWrite), _receivePartCount); return(buffer.Length); } }
public void WriteToFile(StringBuilder sb) { try { if (Directory.Exists(_savepath)) { Directory.Delete(_savepath); } if (File.Exists(_savepath + _filename + ".csv")) { string[] arr_file = null; if (_filename.Contains("_")) { arr_file = _filename.Split('_'); } else { arr_file[0] = _filename; } _filename = arr_file[0] + "_" + _filenamepostfix; _filenamepostfix += 1; } using (FileStream fs = new FileStream(_savepath + _filename + ".csv", FileMode.Append, FileAccess.Write, FileShare.Read, 8, true)) { byte[] bt = System.Text.ASCIIEncoding.ASCII.GetBytes(sb.ToString()); fs.BeginWrite(bt, 0, bt.Length, OnwriteCompleted, fs); } } catch { } }
private void WriteThread(object o) { #if TEST_AS_FRENCH Tools.SetThreadToFrench(); #endif int fileAlignment = (int)o; string idxFile = Path.ChangeExtension(archiveFile, ".idx"); MemoryStream memoryIdx = new MemoryStream(4000 * 4); int bytesWrittenSoFar = 0; int writeIndexSoFar = 0; GT2.RefCounter completeWriteCount = new GT2.RefCounter(); FileStream archive = new FileStream(archiveFile, FileMode.Create, FileAccess.Write, FileShare.None, UInt16.MaxValue, true); using (BinaryWriter idxWriter = new BinaryWriter(memoryIdx)) { WaitHandle[] waitables = new WaitHandle[2] { newWriteSignal, exitEvent }; bool exitLoop = false; while (!exitLoop) { int signalled = WaitHandle.WaitAny(waitables, Timeout.Infinite, false); if (signalled == 0) { int count; lock (writeData) { count = writeData.Count; } while (writeIndexSoFar < count) { // the reads can complete out of order, but we need to write the archive file // in order. So if the alert we got wasn't for the next file, go back and wait // this is also why it's a while loop, so that when we eventually get the signal // for the next file, we can process the other ones we've aleady seen the signal for byte[] nextData = writeData[writeIndexSoFar]; if (nextData != null) { WriteState ws = new WriteState(archive, completeWriteCount); int dataLen = nextData.Length; int lengthWithAlignment = dataLen; int padAmount = 0; if (fileAlignment > 0) { lengthWithAlignment = (lengthWithAlignment + fileAlignment) & ~fileAlignment; padAmount = lengthWithAlignment - dataLen; Array.Resize(ref nextData, lengthWithAlignment); } archive.Position = bytesWrittenSoFar; archive.BeginWrite(nextData, 0, lengthWithAlignment, new AsyncCallback(WriteComplete), ws); idxWriter.Write(bytesWrittenSoFar | padAmount); bytesWrittenSoFar += lengthWithAlignment; ++writeIndexSoFar; } } } else { exitLoop = true; } Debug.Assert(signalled >= 0 && signalled <= 1, "Archive write thread got a signal other than 0 or 1!"); } } bool cancelled = (Thread.VolatileRead(ref wasFinished) == 0); if (!cancelled) { using (BinaryWriter idxFileWriter = new BinaryWriter(new FileStream(idxFile, FileMode.Create, FileAccess.Write, FileShare.None))) { // how many idxFileWriter.Write(writeIndexSoFar); // the offsets idxFileWriter.Write(memoryIdx.ToArray()); // file size idxFileWriter.Write(bytesWrittenSoFar); } } while (!completeWriteCount.HasReached(writeIndexSoFar)) { Thread.Sleep(100); } archive.Dispose(); if (cancelled) { File.Delete(archiveFile); } }
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 AddFrame(Bitmap bmp) { if (bmp.PixelFormat != m_pix_fmt) { return(false); } BitmapData bdat = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, bmp.PixelFormat); BinaryWriter bw = new BinaryWriter(new MemoryStream()); if (!m_header_written) { m_bitmapsize = (uint)(bdat.Stride * bdat.Height); //m_stream.SetLength( (long)(0xdc + (m_bitmapsize + 0x8) * m_frames) ); /*m_main_avi_header.dwWidth = (uint)bdat.Width; * m_main_avi_header.dwHeight = (uint)bdat.Height;// bmp%infoHeader%Height * m_main_avi_header.dwMaxBytesPerSec = (uint)((float)bdat.Stride * (float)bdat.Height * (float)m_rate / (float)m_scale); * m_main_avi_header.dwStreams = 1; * m_main_avi_header.dwSuggestedBufferSize = (uint)(bdat.Stride * bdat.Height); * * AVIStreamHeader stream_header = new AVIStreamHeader(); * stream_header.fccType = Util.mmioFOURCC( "vids" ); * stream_header.fccHandler = 0; * stream_header.dwFlags = 0; * stream_header.dwReserved1 = 0; * stream_header.dwInitialFrames = 0; * stream_header.dwScale = m_scale; * stream_header.dwRate = m_rate; * stream_header.dwStart = 0; * stream_header.dwSuggestedBufferSize = m_main_avi_header.dwSuggestedBufferSize; * stream_header.dwQuality = 0; * stream_header.dwSampleSize = 0; * * BITMAPINFOHEADER bih = new BITMAPINFOHEADER(); //(BITMAPINFOHEADER)Marshal.PtrToStructure( Marshal.AllocHGlobal( sizeof( BITMAPINFOHEADER ) ), typeof( BITMAPINFOHEADER ) ); * bih.biSize = (uint)(Marshal.SizeOf( bih )); * bih.biWidth = bdat.Width; * bih.biHeight = bdat.Height; * bih.biPlanes = 1; * bih.biBitCount = m_pix_fmt == PixelFormat.Format24bppRgb ? (short)24 : (short)32; * bih.biCompression = 0;//BI_RGB * bih.biSizeImage = (uint)(bdat.Stride * bdat.Height); * bih.biXPelsPerMeter = 0; * bih.biYPelsPerMeter = 0; * bih.biClrUsed = 0; * bih.biClrImportant = 0; * * bw.Write( "RIFF".ToCharArray() ); * bw.Write( (uint)(0xdc + (m_bitmapsize + 0x8) * m_frames) ); * bw.Write( "AVI ".ToCharArray() ); * bw.Write( "LIST".ToCharArray() ); * bw.Write( (uint)0xc0 ); * bw.Write( "hdrl".ToCharArray() ); * bw.Write( "avih".ToCharArray() ); * bw.Write( (uint)0x38 ); * m_main_avi_header.Write( bw.BaseStream ); * bw.Write( "LIST".ToCharArray() ); * bw.Write( (uint)0x7C ); * bw.Write( "strl".ToCharArray() ); * bw.Write( "strh".ToCharArray() ); * bw.Write( (uint)0x38 ); * stream_header.Write( bw.BaseStream ); * bw.Write( (uint)0x0 ); * bw.Write( (uint)0x0 ); * bw.Write( "strf".ToCharArray() ); * bw.Write( (uint)0x28 ); * bih.Write( bw.BaseStream ); * bw.Write( "LIST".ToCharArray() ); * bw.Write( (uint)((m_bitmapsize + 0x8) * m_frames) ); * bw.Write( "movi".ToCharArray() );*/ m_header_written = true; } //bw.Write( "00db" ); //bw.Write( (uint)m_bitmapsize ); int address = bdat.Scan0.ToInt32(); byte[] bitmapData = new byte[bdat.Stride * bdat.Height]; Marshal.Copy(new IntPtr(address), bitmapData, 0, bitmapData.Length); //bw.Write( (uint)m_main_avi_header.dwSuggestedBufferSize ); bw.Write("BM".ToCharArray()); bw.Write(m_bitmapsize); bw.Write((uint)0x0); bw.Write((uint)0x36); BITMAPINFOHEADER bih = new BITMAPINFOHEADER(); //(BITMAPINFOHEADER)Marshal.PtrToStructure( Marshal.AllocHGlobal( sizeof( BITMAPINFOHEADER ) ), typeof( BITMAPINFOHEADER ) ); bih.biSize = (uint)(Marshal.SizeOf(bih)); bih.biWidth = bdat.Width; bih.biHeight = bdat.Height; bih.biPlanes = 1; bih.biBitCount = m_pix_fmt == PixelFormat.Format24bppRgb ? (short)24 : (short)32; bih.biCompression = 0;//BI_RGB bih.biSizeImage = (uint)(bdat.Stride * bdat.Height); bih.biXPelsPerMeter = 0; bih.biYPelsPerMeter = 0; bih.biClrUsed = 0; bih.biClrImportant = 0; bih.Write(bw); bw.Write(bitmapData, 0, bitmapData.Length); //const int _BUF_LEN = 512; byte[] buf = new byte[m_bitmapsize + 6]; bw.BaseStream.Seek(0, SeekOrigin.Begin); int len = bw.BaseStream.Read(buf, 0, (int)(m_bitmapsize + 6)); if (len > 0) { m_stream.BeginWrite(buf, 0, len, null, null); } m_stream.Flush(); bw.Close(); bmp.UnlockBits(bdat); return(true); }
public override IAsyncResult BeginWrite(byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject) { return(_fs.BeginWrite(array, offset, numBytes, userCallback, stateObject)); }
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, fs3; Byte[] bReadArr; String filName = s_strTFAbbrev+"Test.tmp"; if(File.Exists(filName)) File.Delete(filName); strLoc = "Loc_98v8v"; iCountTestcases++; try { fs2 = new FileStream(new IntPtr(-1), FileAccess.ReadWrite, true, 0); iCountErrors++; printerr( "Error_987yt! Expected exception not thrown"); } catch (ArgumentException ) { } catch (Exception exc) { iCountErrors++; printerr( "Error_29100! Incorrect exception thrown, exc=="+exc.ToString()); } strLoc = "Loc_498yf"; fs2 = new FileStream(filName, FileMode.Create); fs2.Write(new Byte[]{65,66,67,68,69}, 0, 5); fs2.Flush(); fs2.Position = 0; fs3 = new FileStream(fs2.Handle, FileAccess.Read, false, 8); bReadArr = new Byte[5]; int read = fs3.Read(bReadArr, 0, 5); int i = 65; foreach (Byte b in bReadArr) { iCountTestcases++; if(b != i) { iCountErrors++; printerr( "Error_47f7v_"+i+"! Expected=="+i+" , got=="+b); } i++; } fs2.Close(); fs3.Close(); strLoc = "Loc_487ty"; iCountTestcases++; try { fs2 = new FileStream(new IntPtr(2), (FileAccess)(-2), true, 2000); iCountErrors++; printerr( "Error_f489y! Expected exception not thrown"); } catch (ArgumentException aexc) { printinfo( "Info_4t98c! Caught expected exception, aexc=="+aexc.Message); } catch (Exception exc) { iCountErrors++; printerr( "Error_4398g! Incorrect exception thrown, exc=="+exc.ToString()); } strLoc = "Loc_399f9"; fs2 = new FileStream(filName, FileMode.Create); fs3 = new FileStream(fs2.Handle, FileAccess.Read, true, 4000); fs3.Close(); iCountTestcases++; try { fs2.Write(new Byte[]{1}, 0, 1); fs2.Flush(); iCountErrors++; printerr( "Error_3f8vc! Expected exception not thrown"); } catch (IOException iexc) { printinfo( "Info_398fc! Caught expected exception, iexc=="+iexc.Message); } catch (Exception exc) { iCountErrors++; printerr( "Error_98gyg! Incorrect exception thrown, exc=="+exc.ToString()); } fs2.Close(); strLoc = "Loc_99f99"; fs2 = new FileStream(filName, FileMode.Create); fs3 = new FileStream(fs2.Handle, FileAccess.Read, false, 16000); fs3.Close(); try { fs2.Write(new Byte[]{1}, 0, 1); fs2.Flush(); } catch (Exception exc) { iCountErrors++; printerr( "Error_3989c! Unexpected exception, exc=="+exc.ToString()); } fs2.Close(); strLoc = "Loc_498vy"; fs2 = new FileStream("Bug.txt", FileMode.Create); try { fs3 = new FileStream(fs2.Handle, FileAccess.ReadWrite, false, Int32.MaxValue/100); Byte[] bArr = new Byte[100*10]; for(int ii = 0 ; ii < bArr.Length ;ii++) bArr[i] = (Byte)ii; IAsyncResult iar = fs3.BeginWrite(bArr, 0, bArr.Length, null, null); fs3.EndWrite(iar); fs3.Close(); fs2.Close(); } catch( Exception e ) { Console.WriteLine("Unexpected exception occured... " + e.ToString() ); } File.Delete("Bug.txt"); 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; } }
// Enqueue an async write of the data currently being buffered, then zero out the buffer in // preparation for more appends private void QueueWrite() { handle.BeginWrite(bufferedData.data, 0, (int)bufferedData.validLength, WriteComplete, bufferedCompletions); bufferedData = null; bufferedCompletions = null; }
public IEnumerator LoadAndSaveResources() { downLoadPercent = 0; index = 0; string resourcesFileUrl = resourcesUrl + ClientConfigure.resourceTxtName; string resourceFilePath = Path.Combine(destDir, ClientConfigure.resourceTxtName); WWW www = null; //下载资源文件,如果资源文件下载失败,则重复下载资源文件; SetLabelText("正在获取资源列表"); www = new WWW(resourcesFileUrl); yield return(www); if (!string.IsNullOrEmpty(www.error)) { Debug.LogError(www.error); BoxManager.showMessage("获取资源列表失败,请重试", ClientConfigure.title); UIEventListener.Get(BoxManager.buttonYes).onClick += ReconnectResources; yield break; } //分离资源,判断资源文件的有效性; string[] resourcesRow = www.text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); yield return(null); if (resourcesRow.Length == 0) { Debug.Log("Doesn't have resources"); yield break; } List <string> filePathLists = new List <string>(); for (int i = 0; i < resourcesRow.Length; i++) { string[] strs = resourcesRow[i].Split('\t'); filePathLists.Add(strs[0]); } string[] filePaths = filePathLists.ToArray(); filePathLists.Clear(); /* * 资源存在版本校验的一些处理;目前不做了; * //资源文件列表字典化,方便与本地资源列表对比; * Dictionary<string,int> resourcesDic = new Dictionary<string, int>(); * foreach(string resourceUrl in resourcesRow){ * DownloaderItem resourceItem = new DownloaderItem(resourceUrl); * resourcesDic.Add(resourceItem.name,resourceItem.version); * } * yield return null; * * //如果存在本地资源文件列表,则提取本地资源文件列表并字典化; * //否则直接存储至目标位置; * string[] localResourcesRow = null; * Dictionary<string,int> localResourcesDic = new Dictionary<string, int>(); * bool useLocalResourcesTxt = false; * string resourceFilePath = destDir+"/resources.txt"; * if(!File.Exists(resourceFilePath)){ * Debug.Log("write resource txt file"); * File.WriteAllText(resourceFilePath,www.text); * }else{ * MemoryStream wwwTxtMemory = new MemoryStream(www.bytes); * MemoryStream localTxtMemory = new MemoryStream(File.ReadAllBytes(resourceFilePath)); * * if(wwwTxtMemory.GetHashCode() == localTxtMemory.GetHashCode()){ * useLocalResourcesTxt = false; * }else{ * useLocalResourcesTxt = true; * localResourcesRow = File.ReadAllLines(resourceFilePath); * foreach(string resourceUrl in localResourcesRow){ * DownloaderItem resourceItem = new DownloaderItem(resourceUrl); * localResourcesDic.Add(resourceItem.name,resourceItem.version); * } * } * } * yield return null; */ SetLabelText("正在下载资源文件"); resourcesCount = resourcesRow.Length; List <string> downloadFailedResources = new List <string>(); foreach (string resourcesName in filePaths) { string filePath = Path.Combine(destDir, resourcesName); if (!File.Exists(filePath)) { www = new WWW(resourcesUrl + resourcesName); yield return(www); if (!string.IsNullOrEmpty(www.error)) { Debug.LogError(www.error); downloadFailedResources.Add(resourcesName); } else { string dirPath = Path.GetDirectoryName(filePath); if (!Directory.Exists(dirPath)) { Debug.Log("create dir:" + dirPath); Directory.CreateDirectory(dirPath); } Debug.Log("asyn write start:" + filePath); if (www.bytes.Length < 1024 * 256) { File.WriteAllBytes(filePath, www.bytes); } else { FileStream fileStream = File.OpenWrite(filePath); fileStream.BeginWrite(www.bytes, 0, www.bytes.Length, new AsyncCallback(WriteDone), fileStream); } //File.WriteAllBytes(filePath,www.bytes); } } index++; downLoadPercent = ((float)index) / resourcesCount; yield return(null); } //继续下载下载过程中下载失败的资源文件; while (downloadFailedResources.Count != 0) { string resourcesName = downloadFailedResources[0]; string filePath = Path.Combine(destDir, resourcesName); if (!File.Exists(filePath)) { www = new WWW(resourcesUrl + resourcesName); yield return(www); if (!string.IsNullOrEmpty(www.error)) { Debug.LogError("reDownload:" + www.error); } else { string dirPath = Path.GetDirectoryName(filePath); if (!Directory.Exists(dirPath)) { Debug.LogWarning("reDownload create dir:" + dirPath); Directory.CreateDirectory(dirPath); } Debug.Log("asyn write start:" + filePath); if (www.bytes.Length < 1024 * 256) { File.WriteAllBytes(filePath, www.bytes); } else { FileStream fileStream = File.OpenWrite(filePath); fileStream.BeginWrite(www.bytes, 0, www.bytes.Length, new AsyncCallback(WriteDone), fileStream); } downloadFailedResources.RemoveAt(0); } } yield return(null); } if (!File.Exists(resourceFilePath)) { Debug.Log("write resource txt file"); File.WriteAllText(resourceFilePath, www.text); } downLoadOver = true; yield return(null); }
/// <summary> /// 批量写入日志 /// </summary> /// <param name="log"></param> public void WriteLog(string log) { if (string.IsNullOrEmpty(DataLogFile)) { return; } if (string.IsNullOrEmpty(log)) { return; } lock (sync_obj) { _logBuffer.Add(log); if (_logBuffer.Count > 0 && (DateTime.Now.Subtract(_lastWrite).TotalSeconds > WriteTime || _logBuffer.Count > LogBufferCount)) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.AppendLine("--SQLLog (Thread ID " + System.Threading.Thread.CurrentThread.ManagedThreadId + ") Write Buffer:----"); bool flag = false; foreach (string item in _logBuffer) { if (!item.StartsWith("--SQLLog")) { flag = true; } sb.AppendLine(item); } _logBuffer.Clear(); if (!flag) { return;//没有实质性的日志,不写入日志文件 } string writeText = sb.ToString(); try { //日志文件超过5M,备份日志文件 if (!System.IO.File.Exists(DataLogFile)) { File.AppendAllText(DataLogFile, "--SOD Log Ver 5.6--\r\n", System.Text.Encoding.UTF8); } var fileInfo = new FileInfo(DataLogFile); if (fileInfo.Length > 5 * 1024 * 1024) { string bakFile = string.Format("{0}_{1}.{2}", System.IO.Path.GetFileNameWithoutExtension(DataLogFile), DateTime.Now.ToString("yyyyMMddHHmmss"), System.IO.Path.GetExtension(DataLogFile)); string bakFilePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(DataLogFile), bakFile); System.IO.File.Move(DataLogFile, bakFilePath); } //edit at 2012.10.17 改成无锁异步写如日志文件,2017.9.30日修改,增加说明 //不能将fs 放到Using下面,会导致句柄无效 FileStream fs = new FileStream(DataLogFile, FileMode.Append, FileAccess.Write, FileShare.Write, 2048, FileOptions.Asynchronous); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(writeText); IAsyncResult writeResult = fs.BeginWrite(buffer, 0, buffer.Length, (asyncResult) => { bool isOK = false; FileStream fStream = (FileStream)asyncResult.AsyncState; try { fStream.EndWrite(asyncResult); fStream.Flush(); isOK = true; } catch (Exception ex2) { writeText = "*** 异步结束 写日志文件异常,错误原因:" + ex2.Message + "\r\n 原始日志信息:" + writeText + " \r\n***\r\n"; } finally { fStream.Close(); } if (!isOK) { File.AppendAllText(DataLogFile, writeText); } }, fs); //fs.EndWrite(writeResult);//在这里调用异步起不到效果 //fs.Flush();//异步写入时,刷新缓存可能会导致写入两条数据到文件 } catch (Exception ex) { writeText = "*** 异步开始写日志文件异常,错误原因:" + ex.Message + "\r\n 原始日志信息:" + writeText + " \r\n***\r\n"; File.AppendAllText(DataLogFile, writeText); } _lastWrite = DateTime.Now; } } }
private IEnumerator DownloadCoroutine() { WWW www = null; if (cached) www = new WWW("file://" + Application.temporaryCachePath + "/" + this.guid + ".png"); else www = new WWW(url); #if DEBUG_LOG Debug.Log("DEBUG: TileEntry.DownloadCoroutine: (down)loading from tile url: " + www.url); #endif yield return www; if (www.error == null && www.text.Contains("404 Not Found") == false) { if (www.texture.isBogus()) { #if DEBUG_LOG Debug.LogError("DEBUG: TileEntry.DownloadCoroutine: image from cache is bogus, trying to download it: " + www.url + " [" + url + "]"); #endif //TileDownloader.Instance.DeleteCachedTile(this); //TileDownloader.Instance.Get(url, material); error = true; } else { material.mainTexture = www.texture; material.mainTexture.wrapMode = TextureWrapMode.Clamp; material.mainTexture.filterMode = FilterMode.Trilinear; if (this.cached == false) { // write the png asynchroneously byte[] bytes = (material.mainTexture as Texture2D).EncodeToPNG(); this.size = bytes.Length; this.timestamp = (DateTime.Now - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds; this.guid = Guid.NewGuid().ToString(); FileStream fs = new FileStream(Application.temporaryCachePath + "/" + this.guid + ".png", FileMode.Create); fs.BeginWrite(bytes, 0, bytes.Length, new AsyncCallback(EndWriteCallback), this); #if DEBUG_LOG Debug.Log("DEBUG: TileEntry.DownloadCoroutine: done downloading: " + www.url + ", writing to cache: " + fs.Name); #endif } else { #if DEBUG_LOG Debug.Log("DEBUG: TileEntry.DownloadCoroutine: done loading from cache: " + www.url + " [" + url + "]"); #endif } } } else { error = true; #if DEBUG_LOG Debug.LogError("ERROR: TileEntry.DownloadCoroutine: done downloading: " + www.url + " with error: " + www.error + " (" + www.text + ")"); #endif } }
static System.Collections.IEnumerator AsyncCopyDirRoutine(string srcDirPath, string destDirPath, Action <CopyDirResult> resultCallback) { srcDirPath = FilterPath(srcDirPath); destDirPath = FilterPath(destDirPath); bool hasError = false; float currentFileCopied = 0; string[] filesPath = Directory.GetFiles(srcDirPath, "*.*", SearchOption.AllDirectories); CopyDirResult resultData = new CopyDirResult(); for (int x = 0; x < filesPath.Length; x++) { string filePath = filesPath[x]; string fileName = GetFileName(filePath); if (_cancelAsyncCopyDir || hasError) { break; } try { using (FileStream sourceStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { string fileRelativePath = filePath.Replace(srcDirPath, ""); byte[] srcBuffer = new byte[sourceStream.Length]; try { sourceStream.Read(srcBuffer, 0, srcBuffer.Length); DirectoryInfo dirInfo = Directory.GetParent(destDirPath + fileRelativePath); if (!dirInfo.Exists) { Directory.CreateDirectory(dirInfo.FullName); } } catch { resultData.Initialize(fileName, false, true, currentFileCopied / filesPath.Length); hasError = true; break; } if (!hasError) { FileStream destStream = new FileStream(destDirPath + fileRelativePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); destStream.BeginWrite(srcBuffer, 0, srcBuffer.Length, new AsyncCallback((result) => { FileWriteAsyncInfo info = (FileWriteAsyncInfo)result.AsyncState; try { info.Stream.EndWrite(result); currentFileCopied++; if (File.Exists(destDirPath + fileRelativePath)) { resultData.Initialize(GetFileName(fileRelativePath), true, currentFileCopied == filesPath.Length, currentFileCopied / filesPath.Length); } else { resultData.Initialize(GetFileName(fileRelativePath), false, currentFileCopied == filesPath.Length, currentFileCopied / filesPath.Length); } } catch { resultData.Initialize(GetFileName(fileRelativePath), false, currentFileCopied == filesPath.Length, currentFileCopied / filesPath.Length); hasError = true; } info.Stream.Close(); }), new FileWriteAsyncInfo(destStream)); } } } catch { resultData.Initialize("???", false, true, 0); hasError = true; break; } if (resultCallback != null) { resultCallback(resultData); } yield return(new WaitForSeconds(0.1f)); } // Caso a copia seja cancelada ou tenha acontecido algum erro // tentamos apagar o que foi copiado if (_cancelAsyncCopyDir || hasError) { TriesToClearAsynCopyWhenCanceled(destDirPath); resultData.IsDone = true; resultData.SuccessfullyCopied = false; resultData.HasError = hasError; resultData.WasCancelled = _cancelAsyncCopyDir; if (resultCallback != null) { resultCallback(resultData); } _cancelAsyncCopyDir = false; } }
public static void AsyncCopyFile(string srcPath, string dstPath, string fileName, Action <CopyDirResult> resultCallback) { srcPath = FilterPath(srcPath); dstPath = FilterPath(dstPath); if (!File.Exists(srcPath + fileName)) { if (resultCallback != null) { resultCallback(new CopyDirResult(fileName, false, true, 0)); } return; } using (FileStream sourceStream = new FileStream(srcPath + fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { byte[] srcBuffer = new byte[sourceStream.Length]; try { sourceStream.Read(srcBuffer, 0, srcBuffer.Length); if (!Directory.Exists(dstPath)) { Directory.CreateDirectory(dstPath); } } catch { if (resultCallback != null) { resultCallback(new CopyDirResult(fileName, false, true, 0)); } return; } FileStream destStream = new FileStream(dstPath + fileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); destStream.BeginWrite(srcBuffer, 0, srcBuffer.Length, new AsyncCallback((result) => { FileWriteAsyncInfo info = (FileWriteAsyncInfo)result.AsyncState; try { info.Stream.EndWrite(result); if (File.Exists(dstPath + fileName)) { if (resultCallback != null) { resultCallback(new CopyDirResult(fileName, true, true, 1)); } } else if (resultCallback != null) { resultCallback(new CopyDirResult(fileName, false, true, 0)); } } catch { if (resultCallback != null) { resultCallback(new CopyDirResult(fileName, false, true, 0)); } } info.Stream.Close(); }), new FileWriteAsyncInfo(destStream)); } }
private static void AsyncWriteImg(string path, string fileName, byte[] imgBytes, Action <int> resultCallback) { string[] filterFileName = fileName.Split('.'); fileName = filterFileName.Length > 1 ? filterFileName[0] : fileName; string absolutePath = path + fileName + ".png"; // Add a index to the img name if the name matchs a already created one int counter = 1; try { while (File.Exists(absolutePath)) { absolutePath = path + fileName + string.Format(" ({0})", counter) + ".png"; counter++; } } catch { if (resultCallback != null) { resultCallback(SAVE_IMAGE_CODE_UNKNOW_ERROR); } } FileStream stream = null; try { stream = new FileStream(absolutePath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite, imgBytes.Length); stream.BeginWrite(imgBytes, 0, imgBytes.Length, new AsyncCallback((result) => { FileWriteAsyncInfo info = (FileWriteAsyncInfo)result.AsyncState; try { info.Stream.EndWrite(result); if (File.Exists(absolutePath)) { if (resultCallback != null) { resultCallback(SAVE_IMAGE_CODE_SUCCESS); } } else if (resultCallback != null) { resultCallback(SAVE_IMAGE_CODE_UNKNOW_ERROR); } } catch { if (resultCallback != null) { resultCallback(SAVE_IMAGE_CODE_UNKNOW_ERROR); } } info.Stream.Close(); }), new FileWriteAsyncInfo(stream)); } catch { if (stream != null) { stream.Close(); } if (resultCallback != null) { resultCallback(SAVE_IMAGE_CODE_UNKNOW_ERROR); } } }
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); 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; } }
private IEnumerator DownloadCoroutine() { WWW www = null; string ext = Path.GetExtension(url); if (ext.Contains("?")) ext = ext.Substring(0, ext.IndexOf('?')); #if !UNITY_WEBPLAYER if (cached && File.Exists(Application.temporaryCachePath + "/" + this.guid + ext)) { www = new WWW("file:///" + Application.temporaryCachePath + "/" + this.guid + ext); #if DEBUG_LOG Debug.Log("DEBUG: TileDownloader.DownloadCoroutine: loading tile from cache: url: " + www.url); #endif } else #endif { www = new WWW(url); #if DEBUG_LOG Debug.Log("DEBUG: TileDownloader.DownloadCoroutine: loading tile from provider: url: " + www.url #if !UNITY_WEBPLAYER + "(cached: " + cached + ")" #endif ); #endif } yield return www; #if DEBUG_PROFILE UnitySlippyMap.Profiler.Begin("TileDownloader.TileEntry.DownloadCoroutine"); #endif #if DEBUG_PROFILE UnitySlippyMap.Profiler.Begin("www error test"); #endif if (www.error == null && www.text.Contains("404 Not Found") == false) { #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("www error test"); #endif #if DEBUG_PROFILE UnitySlippyMap.Profiler.Begin("www.texture"); #endif Texture2D texture = new Texture2D(1, 1, TextureFormat.ARGB32, true); www.LoadImageIntoTexture(texture); #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("www.texture"); #endif #if DEBUG_PROFILE UnitySlippyMap.Profiler.Begin("is cached?"); #endif #if !UNITY_WEBPLAYER if (this.cached == false) { #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("is cached?"); #endif #if DEBUG_PROFILE UnitySlippyMap.Profiler.Begin("set TileEntry members"); #endif byte[] bytes = www.bytes; this.size = bytes.Length; this.guid = Guid.NewGuid().ToString(); #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("set TileEntry members"); #endif #if DEBUG_PROFILE UnitySlippyMap.Profiler.Begin("new FileStream & FileStream.BeginWrite"); #endif FileStream fs = new FileStream(Application.temporaryCachePath + "/" + this.guid + ext, FileMode.Create, FileAccess.Write, FileShare.None, 4096, true); fs.BeginWrite(bytes, 0, bytes.Length, new AsyncCallback(EndWriteCallback), new AsyncInfo(this, fs)); #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("new FileStream & FileStream.BeginWrite"); #endif #if DEBUG_LOG Debug.Log("DEBUG: TileEntry.DownloadCoroutine: done loading: " + www.url + ", writing to cache: " + fs.Name); #endif } else { #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("is cached?"); #endif #if DEBUG_LOG Debug.Log("DEBUG: TileEntry.DownloadCoroutine: done loading from cache: " + www.url + " [" + url + "]"); #endif } this.timestamp = (DateTime.Now - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds; #endif #if DEBUG_PROFILE UnitySlippyMap.Profiler.Begin("Tile.SetTexture"); #endif tile.SetTexture(texture); #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("Tile.SetTexture"); #endif } else { #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("www error test"); #endif this.error = true; #if DEBUG_LOG Debug.LogError("ERROR: TileEntry.DownloadCoroutine: done downloading: " + www.url + " with error: " + www.error); #endif } #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("TileDownloader.TileEntry.DownloadCoroutine"); #endif }
/// <summary> /// Begins then operation to creates a new file, writes the specified byte array to the file, and then /// closes the file. If the target file already exists, it is overwritten. /// If the target directory is not existing then create it. /// </summary> /// <param name="path"></param> /// <param name="data"></param> /// <param name="offset"></param> /// <param name="length"></param> /// <param name="bufferSize"></param> /// <param name="callback"></param> /// <param name="userState"></param> /// <returns></returns> public static IAsyncResult BeginWriteAllBytes(string path, byte[] data, int offset, int length, int bufferSize, AsyncCallback callback, object userState) { if (string.IsNullOrWhiteSpace(path)) { throw new ArgumentException("Fiel path is null or empty.", "path"); } if (data == null) { throw new ArgumentNullException("data"); } Exception syncError = null; AsyncResult result = new AsyncResult(callback, userState); try { CreateFolder(path); } catch (Exception ex) { syncError = ex; } if (syncError != null) { result.MarkCompleted(syncError, true); return(result); } FileStream writer = null; try { writer = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, bufferSize, true); } catch (Exception ex) { syncError = ex; } if (syncError != null) { result.MarkCompleted(syncError, true); return(result); } if (writer.IsAsync) { try { writer.BeginWrite(data, offset, length, (ar) => { Exception asyncError = null; try { using (FileStream fs = (FileStream)ar.AsyncState) { fs.EndWrite(ar); } } catch (Exception ex) { asyncError = ex; } result.MarkCompleted(asyncError, false); }, writer); } catch (Exception ex) { syncError = ex; } if (syncError != null) { result.MarkCompleted(syncError, true); } } else { try { using (writer) { writer.Write(data, offset, length); } } catch (Exception ex) { syncError = ex; } result.MarkCompleted(syncError, true); } return(result); }
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); } }
private void OnBytesReceived(Task <int> future) { Log("On bytes received"); var size = future.Result; Log($"Received {size}"); if (size.Equals(0)) { if (remainingBytes > 0) { Log("Closing early... did not finish downloading"); } else { Log("Closing..."); } _conn.Close(); _fileStream.Close(); return; } string output = Encoding.Default.GetString(_buffer).Substring(0, size); //Log(output); switch (_state) { case State.ReadingHeaders: _headers += output; if (_headers.Contains("\r\n\r\n")) { int index = _headers.IndexOf("\r\n\r\n"); string headers = _headers.Substring(0, index); string body = _headers.Substring(index + 4); var regex = new Regex("Content-Length: \\d+"); string matched = regex.Match(headers).Value; if (matched.Length.Equals(0)) { Log("Length header not present...exiting"); _conn.Close(); _fileStream.Close(); return; } remainingBytes = int.Parse(matched.Substring(16)) - body.Length; _state = State.ReadingBody; _fileStream.BeginWrite(Encoding.ASCII.GetBytes(body), 0, body.Length, result => { _fileStream.EndWrite(result); }, null); } break; case State.ReadingBody: remainingBytes -= output.Length; _fileStream.BeginWrite(Encoding.ASCII.GetBytes(output), 0, output.Length, result => { _fileStream.EndWrite(result); }, null); break; } Receive(_buffer, 0, _buffer.Length).ContinueWith(OnBytesReceived); }
public async void Start(IPAddress ipAddress, string request) { Log($"starting {_filePath}"); bool isConnected = await Connect(ipAddress); if (!isConnected) { Log("Could not connect"); _fileStream.Close(); return; } int sentBytes = await Send(Encoding.ASCII.GetBytes(request), 0, request.Length); if (!sentBytes.Equals(request.Length)) { Log("Could not send request"); _fileStream.Close(); _conn.Close(); } else { while (true) { Log("On bytes received"); var size = await Receive(_buffer, 0, _buffer.Length); Log($"Received {size}"); if (size.Equals(0)) { if (remainingBytes > 0) { Log("Closing early... did not finish downloading"); } else { Log("Closing..."); } _conn.Close(); _fileStream.Close(); return; } string output = Encoding.Default.GetString(_buffer).Substring(0, size); switch (_state) { case State.ReadingHeaders: _headers += output; if (_headers.Contains("\r\n\r\n")) { int index = _headers.IndexOf("\r\n\r\n"); string headers = _headers.Substring(0, index); string body = _headers.Substring(index + 4); var regex = new Regex("Content-Length: \\d+"); string matched = regex.Match(headers).Value; if (matched.Length.Equals(0)) { Log("Length header not present...exiting"); _conn.Close(); _fileStream.Close(); return; } remainingBytes = int.Parse(matched.Substring(16)) - body.Length; _state = State.ReadingBody; _fileStream.BeginWrite(Encoding.ASCII.GetBytes(body), 0, body.Length, result => { _fileStream.EndWrite(result); }, null); } break; case State.ReadingBody: remainingBytes -= output.Length; _fileStream.BeginWrite(Encoding.ASCII.GetBytes(output), 0, output.Length, result => { _fileStream.EndWrite(result); }, null); break; } } } }
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return(m_f.BeginWrite(buffer, offset, count, callback, state)); }
private IEnumerator SaveImage(string path, byte[] bytes, Action saveComplete = null) { var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 4096, false); fs.BeginWrite(bytes, 0, bytes.Length, new AsyncCallback (EndWriteCallback), fs); yield return File.Exists (path); if (saveComplete != null) { saveComplete(); } }
public override IEnumerator <CoroutineState> GetEnumerator() { FileStream fileReader = new FileStream( _fileName, FileMode.Open, FileAccess.Read, FileShare.Read, BUFFER_SIZE, true); FileStream fileWriter = new FileStream( Path.Combine(_destinationFolder, Path.GetFileName(_fileName)), FileMode.Create, FileAccess.ReadWrite, FileShare.Write, BUFFER_SIZE, true); int bytesRead = 0; do { //Read asynchronously bool finishedRead = false; IAsyncResult readResult = fileReader.BeginRead(_buffer, 0, BUFFER_SIZE, (asyncResult) => { bytesRead = fileReader.EndRead(asyncResult); finishedRead = true; }, null); //Wait until the reading is complete while (!finishedRead) { //Allow other coroutines to run yield return(CoroutineState.Running); } Console.WriteLine("Finished reading chunk for: " + _fileName); //Write asynchronously bool finishedWriting = false; IAsyncResult writeResult = fileWriter.BeginWrite(_buffer, 0, bytesRead, (asyncResult) => { fileWriter.EndWrite(asyncResult); finishedWriting = true; }, null); //Wait until write is finished while (!finishedWriting) { //Let other coroutines run yield return(CoroutineState.Running); } Console.WriteLine("Finished writing chunk for: " + _fileName); } while (bytesRead > 0); fileReader.Close(); fileWriter.Close(); }
private IEnumerator DownloadCoroutine() { WWW www = null; string ext = Path.GetExtension(url); if (ext.Contains("?")) { ext = ext.Substring(0, ext.IndexOf('?')); } #if !UNITY_WEBPLAYER if (cached && File.Exists(Application.temporaryCachePath + "/" + this.guid + ext)) { www = new WWW("file:///" + Application.temporaryCachePath + "/" + this.guid + ext); #if DEBUG_LOG Debug.Log("DEBUG: TileDownloader.DownloadCoroutine: loading tile from cache: url: " + www.url); #endif } else #endif { www = new WWW(url); #if DEBUG_LOG Debug.Log("DEBUG: TileDownloader.DownloadCoroutine: loading tile from provider: url: " + www.url #if !UNITY_WEBPLAYER + "(cached: " + cached + ")" #endif ); #endif } yield return(www); #if DEBUG_PROFILE UnitySlippyMap.Profiler.Begin("TileDownloader.TileEntry.DownloadCoroutine"); #endif #if DEBUG_PROFILE UnitySlippyMap.Profiler.Begin("www error test"); #endif if (www.error == null && www.text.Contains("404 Not Found") == false) { #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("www error test"); #endif #if DEBUG_PROFILE UnitySlippyMap.Profiler.Begin("www.texture"); #endif Texture2D texture = new Texture2D(1, 1, TextureFormat.ARGB32, true); www.LoadImageIntoTexture(texture); #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("www.texture"); #endif #if DEBUG_PROFILE UnitySlippyMap.Profiler.Begin("is cached?"); #endif #if !UNITY_WEBPLAYER if (this.cached == false) { #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("is cached?"); #endif #if DEBUG_PROFILE UnitySlippyMap.Profiler.Begin("set TileEntry members"); #endif byte[] bytes = www.bytes; this.size = bytes.Length; this.guid = Guid.NewGuid().ToString(); #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("set TileEntry members"); #endif #if DEBUG_PROFILE UnitySlippyMap.Profiler.Begin("new FileStream & FileStream.BeginWrite"); #endif FileStream fs = new FileStream(Application.temporaryCachePath + "/" + this.guid + ext, FileMode.Create, FileAccess.Write, FileShare.None, 4096, true); fs.BeginWrite(bytes, 0, bytes.Length, new AsyncCallback(EndWriteCallback), new AsyncInfo(this, fs)); #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("new FileStream & FileStream.BeginWrite"); #endif #if DEBUG_LOG Debug.Log("DEBUG: TileEntry.DownloadCoroutine: done loading: " + www.url + ", writing to cache: " + fs.Name); #endif } else { #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("is cached?"); #endif #if DEBUG_LOG Debug.Log("DEBUG: TileEntry.DownloadCoroutine: done loading from cache: " + www.url + " [" + url + "]"); #endif } this.timestamp = (DateTime.Now - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds; #endif #if DEBUG_PROFILE UnitySlippyMap.Profiler.Begin("Tile.SetTexture"); #endif tile.SetTexture(texture); #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("Tile.SetTexture"); #endif } else { #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("www error test"); #endif this.error = true; #if DEBUG_LOG Debug.LogError("ERROR: TileEntry.DownloadCoroutine: done downloading: " + www.url + " with error: " + www.error); #endif } #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("TileDownloader.TileEntry.DownloadCoroutine"); #endif }
public void AppendPacket(Input input) { DateTime now = input.time_received; byte[] packet = input.received_packet; Int32 unixTimestamp = (Int32)(now.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; string micro = now.ToString("ffffff"); uint umicro = uint.Parse(micro); Int32 ethernet2_header_length = 14; //-- write packet metaheader byte[] packet_metaheader = new byte[16]; Array.Copy(BitConverter.GetBytes(unixTimestamp), 0, packet_metaheader, 0, 4); Array.Copy(BitConverter.GetBytes(umicro), 0, packet_metaheader, 4, 4); Array.Copy(BitConverter.GetBytes(ethernet2_header_length + packet.Length), 0, packet_metaheader, 8, 4); Array.Copy(BitConverter.GetBytes(ethernet2_header_length + packet.Length), 0, packet_metaheader, 12, 4); NetworkLayerType ptype = Common.GetNetworkLayerType(packet); byte[] type = new byte[2]; switch (ptype) { case NetworkLayerType.IPv4: type = new byte[2] { 0x08, 0x00 }; break; case NetworkLayerType.IPv6: type = new byte[2] { 0x86, 0xDD }; break; case NetworkLayerType.Occ: return; case NetworkLayerType.Empty: return; case NetworkLayerType.Unknown: File.AppendAllText("pcapwriter.log", "pcapwriter err unknown : \r\n" + BitConverter.ToString(packet).Replace("-", "") + "\r\n"); return; default: break; } //-- write ethernet 2 frame byte[] ethernet2_frame = new byte[ethernet2_header_length]; Array.Copy(new byte[6] { 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA }, 0, ethernet2_frame, 0, 6); Array.Copy(new byte[6] { 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB }, 0, ethernet2_frame, 6, 6); Array.Copy(type, 0, ethernet2_frame, 12, 2); //-- write ip packet byte[] record = new byte[packet_metaheader.Length + ethernet2_header_length + packet.Length]; Array.Copy(packet_metaheader, 0, record, 0, packet_metaheader.Length); Array.Copy(ethernet2_frame, 0, record, packet_metaheader.Length, ethernet2_header_length); Array.Copy(packet, 0, record, packet_metaheader.Length + ethernet2_header_length, packet.Length); //-- write to file fs.BeginWrite(record, 0, record.Length, new AsyncCallback(EndWriteCallback), null); return; }
protected override Task WriteAsync(FileStream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken) => Task.Factory.FromAsync( (callback, state) => stream.BeginWrite(buffer, offset, count, callback, state), iar => stream.EndWrite(iar), null);
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 iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; String strValue = String.Empty; try { FileStream fs2, fs3; Byte[] bReadArr; String filName = s_strTFAbbrev + "Test.tmp"; if (File.Exists(filName)) { File.Delete(filName); } strLoc = "Loc_98v8v"; iCountTestcases++; try { fs2 = new FileStream(new IntPtr(-1), FileAccess.ReadWrite, true, 0); iCountErrors++; printerr("Error_987yt! Expected exception not thrown"); } catch (ArgumentException) { } catch (Exception exc) { iCountErrors++; printerr("Error_29100! Incorrect exception thrown, exc==" + exc.ToString()); } strLoc = "Loc_498yf"; fs2 = new FileStream(filName, FileMode.Create); fs2.Write(new Byte[] { 65, 66, 67, 68, 69 }, 0, 5); fs2.Flush(); fs2.Position = 0; fs3 = new FileStream(fs2.Handle, FileAccess.Read, false, 8); bReadArr = new Byte[5]; int read = fs3.Read(bReadArr, 0, 5); int i = 65; foreach (Byte b in bReadArr) { iCountTestcases++; if (b != i) { iCountErrors++; printerr("Error_47f7v_" + i + "! Expected==" + i + " , got==" + b); } i++; } fs2.Close(); fs3.Close(); strLoc = "Loc_487ty"; iCountTestcases++; try { fs2 = new FileStream(new IntPtr(2), (FileAccess)(-2), true, 2000); iCountErrors++; printerr("Error_f489y! Expected exception not thrown"); } catch (ArgumentException aexc) { printinfo("Info_4t98c! Caught expected exception, aexc==" + aexc.Message); } catch (Exception exc) { iCountErrors++; printerr("Error_4398g! Incorrect exception thrown, exc==" + exc.ToString()); } strLoc = "Loc_399f9"; fs2 = new FileStream(filName, FileMode.Create); fs3 = new FileStream(fs2.Handle, FileAccess.Read, true, 4000); fs3.Close(); iCountTestcases++; try { fs2.Write(new Byte[] { 1 }, 0, 1); fs2.Flush(); iCountErrors++; printerr("Error_3f8vc! Expected exception not thrown"); } catch (IOException iexc) { printinfo("Info_398fc! Caught expected exception, iexc==" + iexc.Message); } catch (Exception exc) { iCountErrors++; printerr("Error_98gyg! Incorrect exception thrown, exc==" + exc.ToString()); } fs2.Close(); strLoc = "Loc_99f99"; fs2 = new FileStream(filName, FileMode.Create); fs3 = new FileStream(fs2.Handle, FileAccess.Read, false, 16000); fs3.Close(); try { fs2.Write(new Byte[] { 1 }, 0, 1); fs2.Flush(); } catch (Exception exc) { iCountErrors++; printerr("Error_3989c! Unexpected exception, exc==" + exc.ToString()); } fs2.Close(); strLoc = "Loc_498vy"; fs2 = new FileStream("Bug.txt", FileMode.Create); try { fs3 = new FileStream(fs2.Handle, FileAccess.ReadWrite, false, Int32.MaxValue / 100); Byte[] bArr = new Byte[100 * 10]; for (int ii = 0; ii < bArr.Length; ii++) { bArr[i] = (Byte)ii; } IAsyncResult iar = fs3.BeginWrite(bArr, 0, bArr.Length, null, null); fs3.EndWrite(iar); fs3.Close(); fs2.Close(); } catch (Exception e) { Console.WriteLine("Unexpected exception occured... " + e.ToString()); } File.Delete("Bug.txt"); 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); } }
/// <summary> /// Rollback all transaction root logs. /// NOTE: invoke this upon app restart /// </summary> public static bool RollbackAll(string serverPath) { string logFolder = string.Format("{0}\\TransactionLogs", serverPath); if (System.IO.Directory.Exists(logFolder)) { //** 1.) open each transaction log file in TransactionLog folder and restore the last line activity... string[] logFiles = System.IO.Directory.GetFiles(logFolder, string.Format("{0}*.txt", TransLiteral)); foreach (string logFile in logFiles) { //** open the transaction log file and process contents System.IO.StreamReader reader; try { reader = new System.IO.StreamReader(logFile); } catch { return(false); } using (reader) { reader.BaseStream.Seek(0, System.IO.SeekOrigin.End); if (reader.BaseStream.Position == 0) { reader.Close(); continue; } long seekCount = -256; if (reader.BaseStream.Position < 256) { seekCount = reader.BaseStream.Position * -1; } reader.BaseStream.Seek(seekCount, System.IO.SeekOrigin.End); string s = reader.ReadToEnd(); s = s.TrimEnd(); const string registerSaveLiteral = "RegisterSave "; if (string.IsNullOrEmpty(s) || !s.StartsWith(registerSaveLiteral)) { // do nothing... } else { //** roll back... string values = s.Substring(registerSaveLiteral.Length - 1); string[] parts = values.Split(new string[] { ", " }, StringSplitOptions.None); if (parts != null && parts.Length == 3) { string targetFilename = parts[0].Trim(); int targetBlockAddress; //** TODO: create a restart log file where these exceptions will be logged if (!int.TryParse(parts[1], out targetBlockAddress)) { throw new ApplicationException( string.Format("Invalid Block Address{0} found in log file {1}", parts[1], targetFilename)); } int targetSegmentSize; if (!int.TryParse(parts[2], out targetSegmentSize)) { throw new ApplicationException( string.Format("Invalid _region Size{0} found in log file {1}", parts[2], targetFilename)); } string sourceFilename = string.Format("{0}.log", logFile.Substring(0, logFile.Length - 4)); if (!System.IO.File.Exists(sourceFilename)) { throw new ApplicationException( string.Format("Backup filename{0} not found.", sourceFilename)); } int targetBufferSize; FileStream targetFileStream = File.UnbufferedOpen(ObjectServer.NormalizePath(serverPath, targetFilename), System.IO.FileAccess.ReadWrite, targetSegmentSize, out targetBufferSize); if (targetFileStream == null) { throw new ApplicationException(string.Format("Can't open Target File {0}.", targetFilename)); } int sourceBufferSize; FileStream sourceFileStream = File.UnbufferedOpen( ObjectServer.NormalizePath(serverPath, sourceFilename), System.IO.FileAccess.ReadWrite, targetSegmentSize, out sourceBufferSize); var sourceBuffer = new byte[sourceBufferSize]; targetFileStream.Seek(targetBlockAddress, System.IO.SeekOrigin.Begin); //** copy asynchronously from source to target log file IAsyncResult iar = sourceFileStream.BeginRead(sourceBuffer, 0, targetSegmentSize, null, null); if (!iar.IsCompleted) { iar.AsyncWaitHandle.WaitOne(); } sourceFileStream.EndRead(iar); targetFileStream.Seek(0, System.IO.SeekOrigin.Begin); iar = targetFileStream.BeginWrite(sourceBuffer, 0, targetSegmentSize, null, null); if (!iar.IsCompleted) { iar.AsyncWaitHandle.WaitOne(); } targetFileStream.EndWrite(iar); targetFileStream.Flush(); targetFileStream.Dispose(); sourceFileStream.Dispose(); } } } } foreach (string logFile in logFiles) { ProcessLines(logFile, null, null); Sop.Utility.Utility.FileDelete(logFile); } //** remove TransactionLog folder //System.IO.Directory.Delete(LogFolder, true); return(true); } return(false); }