public void ConstructorAndUpdate() { MockRepository rep = new MockRepository(); DateTime modifTime = new DateTime(2000, 1, 1); long size = 100; MyFileStream stm = rep.CreateMock <MyFileStream>(rep); Expect.Call(() => stm.Dispose()).Repeat.AtLeastOnce(); Expect.Call(stm.Length).Return(size); Expect.Call(stm.IsDeleted).Repeat.Any().Return(false); Expect.Call(stm.LastWriteTime).Repeat.Any().Return(modifTime); IFileSystem fs = rep.CreateMock <IFileSystem>(); Expect.Call(fs.OpenFile("test")).Return(stm); rep.ReplayAll(); using (SimpleFileMedia media = new SimpleFileMedia(fs, SimpleFileMedia.CreateConnectionParamsFromFileName("test"))) { Assert.AreEqual(modifTime, media.LastModified); Assert.AreEqual(size, media.Size); } rep.VerifyAll(); }
public void ExceptionInConstructorMustNotLeakStreams() { MockRepository rep = new MockRepository(); MyFileStream stm = rep.CreateMock <MyFileStream>(rep); stm.Dispose(); LastCall.On(stm).Repeat.AtLeastOnce(); Exception ex = new TestException(); Expect.Call(stm.Length).Repeat.Times(0, 1).Throw(ex); Expect.Call(stm.IsDeleted).Repeat.Times(0, 1).Throw(ex); Expect.Call(stm.LastWriteTime).Repeat.Times(0, 1).Throw(ex); IFileSystem fs = rep.CreateMock <IFileSystem>(); Expect.Call(fs.OpenFile("test")).Return(stm); rep.ReplayAll(); try { (new SimpleFileMedia(fs, SimpleFileMedia.CreateConnectionParamsFromFileName("test"))).Dispose(); } catch (TestException) { } rep.VerifyAll(); }
public void UpdatingWhileFileIsGrowing() { IFileSystem fs = Substitute.For <IFileSystem>(); MyFileStream stm = Substitute.For <MyFileStream>(new object()); fs.OpenFile("test").Returns(stm); DateTime time1 = new DateTime(2000, 1, 1); long size1 = 100; stm.Length.Returns(size1); stm.LastWriteTime.Returns(time1); stm.IsDeleted.Returns(false); using (SimpleFileMedia media = new SimpleFileMedia(fs, SimpleFileMedia.CreateConnectionParamsFromFileName("test"))) { Assert.AreEqual(time1, media.LastModified); Assert.AreEqual(size1, media.Size); Assert.AreEqual(size1, media.DataStream.Length); DateTime time2 = new DateTime(2000, 2, 2); long size2 = 200; stm.Length.Returns(size2); stm.LastWriteTime.Returns(time2); stm.IsDeleted.Returns(false); media.Update(); Assert.AreEqual(time2, media.LastModified); Assert.AreEqual(size2, media.Size); } stm.Received(1).Dispose(); }
public void Finalizer_CallsVirtualDispose_FalseArg() { bool disposeInvoked = false; Action act = () => // separate method to avoid JIT lifetime-extension issues { var fs2 = new MyFileStream(GetTestFilePath(), FileMode.Create) { DisposeMethod = (disposing) => { disposeInvoked = true; Assert.False(disposing, "Expected false arg to Dispose(bool)"); } }; }; act(); for (int i = 0; i < 2; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } Assert.True(disposeInvoked, "Expected finalizer to be invoked and set called"); }
public static void Using(string filename, FileMode mode, Action <MyFileStream> use) { MyFileStream mfs = new MyFileStream(filename, mode); use(mfs); mfs.Dispose(); }
public void NoDispose_CallsVirtualDisposeFalseArg_ThrowsDuringFlushWriteBuffer_FinalizerWontThrow() { RemoteExecutor.Invoke(() => { string fileName = GetTestFilePath(); using (FileStream fscreate = new FileStream(fileName, FileMode.Create)) { fscreate.WriteByte(0); } bool writeDisposeInvoked = false; Action <bool> writeDisposeMethod = (disposing) => { writeDisposeInvoked = true; Assert.False(disposing, "Expected false arg to Dispose(bool)"); }; using (var fsread = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { Action act = () => // separate method to avoid JIT lifetime-extension issues { var fswrite = new MyFileStream(fsread.SafeFileHandle, FileAccess.Write, writeDisposeMethod); fswrite.WriteByte(0); }; act(); // Dispose is not getting called here. // instead, make sure finalizer gets called and doesnt throw exception for (int i = 0; i < 2; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } Assert.True(writeDisposeInvoked, "Expected finalizer to be invoked but not throw exception"); } }).Dispose(); }
public void Dispose_CallsVirtualDispose_TrueArg() { bool disposeInvoked = false; Action act = () => // separate method to avoid JIT lifetime-extension issues { using (MyFileStream fs = new MyFileStream(GetTestFilePath(), FileMode.Create)) { fs.DisposeMethod = (disposing) => { disposeInvoked = true; Assert.True(disposing, "Expected true arg to Dispose(bool)"); }; // Normal dispose should call Dispose(true) fs.Dispose(); Assert.True(disposeInvoked, "Expected Dispose(true) to be called from Dispose()"); disposeInvoked = false; } // Second dispose leaving the using should still call dispose Assert.True(disposeInvoked, "Expected Dispose(true) to be called from Dispose() again"); disposeInvoked = false; }; act(); // Make sure we suppressed finalization for (int i = 0; i < 2; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } Assert.False(disposeInvoked, "Expected finalizer to have been suppressed"); }
public static void DCS_FileStreamSurrogate() { const string TestFileName = "Test.txt"; const string TestFileData = "Some data for data contract surrogate test"; // Create the serializer and specify the surrogate var dcs = new DataContractSerializer(typeof(MyFileStream)); dcs.SetSerializationSurrogateProvider(MyFileStreamSurrogateProvider.Singleton); // Create and initialize the stream byte[] serializedStream; // Serialize the stream using (MyFileStream stream1 = new MyFileStream(TestFileName)) { stream1.WriteLine(TestFileData); using (MemoryStream memoryStream = new MemoryStream()) { dcs.WriteObject(memoryStream, stream1); serializedStream = memoryStream.ToArray(); } } // Deserialize the stream using (MemoryStream stream = new MemoryStream(serializedStream)) { using (MyFileStream stream2 = (MyFileStream)dcs.ReadObject(stream)) { string fileData = stream2.ReadLine(); Assert.StrictEqual(TestFileData, fileData); } } }
public void ZipPathTest() { string outside, inside; MyFileStream.ParseZipPath(@"C:\ForFileManager\ToCheckThreadsWork.zip\ToCheckThreadsWork", out outside, out inside); Assert.AreEqual(@"C:\ForFileManager\ToCheckThreadsWork.zip", outside); Assert.AreEqual(@"ToCheckThreadsWork", inside); }
public void SetFileTest() { Stream stream = File.OpenRead(_patch + "\\test.txt"); var data = new MyFileStream("test.txt", "My Test file set", stream); _service.SetFile(data); Assert.NotNull(""); }
public override void FindSolution() { _set.Add(_total); while (!Iterate()) { _stream.Dispose(); _stream = new MyFileStream(); } }
public void UpdatingWhileFileIsGrowing() { MockRepository rep = new MockRepository(); IFileSystem fs = rep.CreateMock <IFileSystem>(); MyFileStream stm = rep.CreateMock <MyFileStream>(rep); Expect.Call(fs.OpenFile("test")).Return(stm); DateTime time1 = new DateTime(2000, 1, 1); long size1 = 100; Expect.Call(stm.Length).Repeat.Any().Return(size1); Expect.Call(stm.LastWriteTime).Repeat.Any().Return(time1); Expect.Call(stm.IsDeleted).Repeat.Any().Return(false); rep.ReplayAll(); using (SimpleFileMedia media = new SimpleFileMedia(fs, SimpleFileMedia.CreateConnectionParamsFromFileName("test"))) { Assert.AreEqual(time1, media.LastModified); Assert.AreEqual(size1, media.Size); Assert.AreEqual(size1, media.DataStream.Length); rep.VerifyAll(); rep.BackToRecordAll(); DateTime time2 = new DateTime(2000, 2, 2); long size2 = 200; Expect.Call(stm.Length).Repeat.Any().Return(size2); Expect.Call(stm.LastWriteTime).Repeat.Any().Return(time2); Expect.Call(stm.IsDeleted).Repeat.Any().Return(false); rep.ReplayAll(); media.Update(); Assert.AreEqual(time2, media.LastModified); Assert.AreEqual(size2, media.Size); rep.VerifyAll(); rep.BackToRecordAll(); stm.Dispose(); LastCall.On(stm).Repeat.AtLeastOnce(); rep.ReplayAll(); } rep.VerifyAll(); }
public void FlushCallsFlush_toDisk_false() { bool called = false; using (MyFileStream fs = new MyFileStream(GetTestFilePath(), FileMode.Create)) { fs.FlushToDiskMethod = (flushToDisk) => { Assert.False(flushToDisk); called = true; }; fs.Flush(); Assert.True(called); } }
public async Task MediaPropertiesMustChangeOnlyAfterUpdate() { IFileSystem fs = Substitute.For <IFileSystem>(); MyFileStream stm = Substitute.For <MyFileStream>(new object()); fs.OpenFile("test").Returns(stm); DateTime time1 = new DateTime(2000, 1, 1); long size1 = 100; stm.Length.Returns(size1); stm.LastWriteTime.Returns(time1); stm.IsDeleted.Returns(false); using (SimpleFileMedia media = await SimpleFileMedia.Create(fs, SimpleFileMedia.CreateConnectionParamsFromFileName("test"))) { // Media properties are the same as stm's ones Assert.AreEqual(time1, media.LastModified); Assert.AreEqual(size1, media.Size); // Change the properties of stm DateTime time2 = new DateTime(2000, 2, 2); long size2 = 200; stm.Length.Returns(size2); stm.LastWriteTime.Returns(time2); stm.IsDeleted.Returns(false); // Properties have not still changed Assert.AreEqual(time1, media.LastModified); Assert.AreEqual(size1, media.Size); // This Update should refresh media's properties await media.Update(); Assert.AreEqual(time2, media.LastModified); Assert.AreEqual(size2, media.Size); // Subsequent calls change nothing await media.Update(); await media.Update(); Assert.AreEqual(time2, media.LastModified); Assert.AreEqual(size2, media.Size); } stm.Received(1).Dispose(); }
/// <summary> /// Lock the file containing the object from being access by others /// </summary> /// <returns></returns> public FileStream Lock() { Retry <IOException>(() => { stream = new MyFileStream(_filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None, this); }); if (IsChanged()) { Save(); } else { Read(); } return(stream); }
public void Dispose_CallsVirtualDisposeTrueArg_ThrowsDuringFlushWriteBuffer_DisposeThrows() { RemoteInvoke(() => { string fileName = GetTestFilePath(); using (FileStream fscreate = new FileStream(fileName, FileMode.Create)) { fscreate.WriteByte(0); } bool writeDisposeInvoked = false; Action <bool> writeDisposeMethod = _ => writeDisposeInvoked = true; using (var fsread = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { Action act = () => // separate method to avoid JIT lifetime-extension issues { using (var fswrite = new MyFileStream(fsread.SafeFileHandle, FileAccess.Write, writeDisposeMethod)) { fswrite.WriteByte(0); // Normal dispose should call Dispose(true). Throws due to FS trying to flush write buffer Assert.Throws <UnauthorizedAccessException>(() => fswrite.Dispose()); Assert.True(writeDisposeInvoked, "Expected Dispose(true) to be called from Dispose()"); writeDisposeInvoked = false; // Only throws on first Dispose call fswrite.Dispose(); Assert.True(writeDisposeInvoked, "Expected Dispose(true) to be called from Dispose()"); writeDisposeInvoked = false; } Assert.True(writeDisposeInvoked, "Expected Dispose(true) to be called from Dispose() again"); writeDisposeInvoked = false; }; act(); for (int i = 0; i < 2; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } Assert.False(writeDisposeInvoked, "Expected finalizer to have been suppressed"); } return(SuccessExitCode); }).Dispose(); }
public object GetObjectToSerialize(object obj, Type targetType) { if (obj == null) { return(null); } MyFileStream myFileStream = obj as MyFileStream; if (null != myFileStream) { if (targetType != typeof(MyFileStreamReference)) { throw new ArgumentException("Target type for serialization must be MyFileStream"); } return(MyFileStreamReference.Create(myFileStream)); } return(obj); }
public void DisposeVirtualBehavior() { bool called = false; // Normal dispose should call Dispose(true) using (MyFileStream fs = new MyFileStream(GetTestFilePath(), FileMode.Create)) { fs.DisposeMethod = (disposing) => { called = true; Assert.True(disposing); }; fs.Dispose(); Assert.True(called); called = false; } // Second dispose leaving the using should still call dispose Assert.True(called); called = false; // make sure we suppress finalization GC.Collect(); GC.WaitForPendingFinalizers(); Assert.False(called); // Dispose from finalizer should call Dispose(false) called = false; MyFileStream fs2 = new MyFileStream(GetTestFilePath(), FileMode.Create); fs2.DisposeMethod = (disposing) => { called = true; Assert.False(disposing); }; fs2 = null; GC.Collect(); GC.WaitForPendingFinalizers(); Assert.True(called); }
public void ConstructorAndUpdate() { DateTime modifTime = new DateTime(2000, 1, 1); long size = 100; MyFileStream stm = Substitute.For <MyFileStream>(new object()); stm.Length.Returns(size); stm.IsDeleted.Returns(false); stm.LastWriteTime.Returns(modifTime); IFileSystem fs = Substitute.For <IFileSystem>(); fs.OpenFile("test").Returns(stm); using (SimpleFileMedia media = new SimpleFileMedia(fs, SimpleFileMedia.CreateConnectionParamsFromFileName("test"))) { Assert.AreEqual(modifTime, media.LastModified); Assert.AreEqual(size, media.Size); } stm.Received(1).Dispose(); }
public void ExceptionInConstructorMustNotLeakStreams() { MyFileStream stm = Substitute.For <MyFileStream>(new object()); Exception ex = new TestException(); stm.Length.Returns(callInfo => { throw ex; }); stm.IsDeleted.Returns(callInfo => { throw ex; }); stm.LastWriteTime.Returns(callInfo => { throw ex; }); IFileSystem fs = Substitute.For <IFileSystem>(); fs.OpenFile("test").Returns(stm); try { (new SimpleFileMedia(fs, SimpleFileMedia.CreateConnectionParamsFromFileName("test"))).Dispose(); } catch (TestException) { } stm.Received(1).Dispose(); }
// ========================================================================================================= #region ImportRecordFromFile private int ImportRecordFromFile(string fname) { if (Session["UserID"] == null) { Response.Redirect("../close_win.aspx"); } iCount = 0; //ch 200905 //231105 SURAJIT String strSucess = ""; String strFailure = ""; //231105 SURAJIT if (Session["UserID"] != null) { string strUserID = Session["UserID"].ToString().Trim(); SqlConnection objConn = new SqlConnection(CBSAppUtils.PrimaryConnectionString); StreamReader MyFileStream; //230905 SURAJIT try { String fileName = RollDice().ToString().Trim() + ".CSV"; FileInfo fi = new FileInfo(Server.MapPath(ConfigurationManager.AppSettings["UploadExcel"]) + fname); fi.CopyTo(Server.MapPath(ConfigurationManager.AppSettings["UploadExcel"]) + fileName); FileInfo fi1 = new FileInfo(Server.MapPath(ConfigurationManager.AppSettings["UploadExcel"]) + fileName); if (fi1.Exists) { MyFileStream = File.OpenText(Server.MapPath(ConfigurationManager.AppSettings["UploadExcel"]) + fileName); //230905 SURAJIT string MyLine; int i = 1; while (MyFileStream.Peek() != -1) { i++; MyLine = MyFileStream.ReadLine(); string strDocumentType = ""; string strGMGCompany = ""; string strVendor = ""; string strInvoiceDate = ""; string strPONumber = ""; string strInvoiceNumber = ""; string strNetAmount = ""; string strVatAmount = ""; string strTotalAmount = ""; string strCurrency = ""; string strTimePaymentDue = ""; string strRepositoryDocumentID = ""; if (i > 0) { //MyLine = MyLine.Replace("\\","").Replace(" ","").Replace("\"",""); //291105 String[] MyArray = MyLine.Split(','); strDocumentType = MyArray[3].ToString().Trim().Replace("\\", "").Replace(" ", "").Replace("\"", ""); strGMGCompany = MyArray[5].ToString().Trim().Replace("\\", "").Replace(" ", "").Replace("\"", ""); strVendor = MyArray[7].ToString().Trim().Replace("\\", "").Replace(" ", "").Replace("\"", ""); strInvoiceDate = MyArray[9].ToString().Trim().Replace("\\", "").Replace(" ", "").Replace("\"", ""); string invdate1 = ""; string invdate2 = ""; String[] invdate = strInvoiceDate.Split('/'); if (invdate[0].Length < 2) { invdate[0] = '0' + invdate[0]; } if (invdate.Length != 3) //011205 SURAJIT { //strInvoiceDate } else { if (invdate.Length > 1) //301105 SURAJIT { if (invdate[1].Length < 2) { invdate[1] = '0' + invdate[1]; } invdate1 = invdate[1]; } else { invdate1 = ""; //301105 SURAJIT } if (invdate.Length > 2) //301105 SURAJIT { if (invdate[2].Length < 4) { invdate[2] = "20" + invdate[2]; } invdate2 = invdate[2]; } else { invdate2 = ""; //301105 SURAJIT } strInvoiceDate = invdate[0] + '/' + invdate1 + '/' + invdate2; } strPONumber = MyArray[11].ToString().Trim().Replace("\\", "").Replace(" ", "").Replace("\"", ""); strInvoiceNumber = MyArray[13].ToString().Trim().Replace("\\", "").Replace(" ", "").Replace("\"", ""); strNetAmount = MyArray[15].ToString().Trim().Replace("\\", "").Replace(" ", "").Replace("\"", ""); strVatAmount = MyArray[17].ToString().Trim().Replace("\\", "").Replace(" ", "").Replace("\"", ""); strTotalAmount = MyArray[19].ToString().Trim().Replace("\\", "").Replace(" ", "").Replace("\"", ""); strCurrency = MyArray[21].ToString().Trim().Replace("\\", "").Replace(" ", "").Replace("\"", ""); strTimePaymentDue = MyArray[23].ToString().Trim().Replace("\\", "").Replace(" ", "").Replace("\"", ""); strRepositoryDocumentID = MyArray[24].ToString().Trim(); //.Replace("\\","").Replace(" ","").Replace("\"",""); strRepositoryDocumentID = strRepositoryDocumentID.ToLower().Replace("\\\\off-gmg-fin\\invoicerep\\postprocess\\", ""); //http://invoices.gmgradio.com//"); strRepositoryDocumentID = strRepositoryDocumentID.ToLower().Replace("\\\\off-gmg-fin\\invoicerep\\preprocess\\", ""); //http://invoices.gmgradio.com//"); //230905 SURAJIT { //230905 SURAJIT SqlCommand objComm = new SqlCommand("stpAddNewRecordFromExcelIntoInvoice", objConn); objComm.CommandType = CommandType.StoredProcedure; objComm.Parameters.Add("@DocumentType", strDocumentType); //030905 SURAJIT objComm.Parameters.Add("@GMGCompany", strGMGCompany); objComm.Parameters.Add("@Vendor", strVendor); objComm.Parameters.Add("@InvoiceDate", strInvoiceDate); objComm.Parameters.Add("@PONumber", strPONumber); objComm.Parameters.Add("@InvoiceNumber", strInvoiceNumber); objComm.Parameters.Add("@NetAmount", strNetAmount); objComm.Parameters.Add("@VatAmount", strVatAmount); objComm.Parameters.Add("@TotalAmount", strTotalAmount); objComm.Parameters.Add("@Currency", strCurrency); objComm.Parameters.Add("@TimePaymentDue", strTimePaymentDue); objComm.Parameters.Add("@RepositoryDocumentID", strRepositoryDocumentID); objComm.Parameters.Add("@UserID", strUserID); SqlParameter paramReturnValue = objComm.Parameters.Add("ReturnValue", SqlDbType.Int); paramReturnValue.Direction = ParameterDirection.ReturnValue; //291105 int intRecordCount = 0; String msgErr = ""; if (strGMGCompany != "" && invdate.Length > 2) //ch 011205 SURAJIT { try { //291105 objConn.Open(); objComm.ExecuteNonQuery(); } catch (System.Exception Ex0) { msgErr = Ex0.Message; intRecordCount = 0; } //291105 intRecordCount = Convert.ToInt32(objComm.Parameters["ReturnValue"].Value); } objComm.Dispose(); objConn.Close(); if (intRecordCount > 0) { iCount = iCount + 1; strSucess += strInvoiceNumber + ","; //231105 SURAJIT } //231105 SURAJIT else { strFailure += strInvoiceNumber + ","; CreateLog(fi, fileName, i, strDocumentType, strUserID, strGMGCompany, strInvoiceDate, strVendor, strInvoiceNumber); } //231105 SURAJIT }//230905 SURAJIT } totCount = i; //200905 SURAJIT } MyFileStream.Close(); //230905 SURAJIT if (fi.Exists) { fi.Delete(); } if (fi1.Exists) { fi1.Delete(); } } else { lblErr.Text = "File is already exclusively open by another user. Please close the file and try again."; } } catch (System.Exception Ex1) { lblErr.Text = Ex1.Message; } //230905 SURAJIT } return(iCount); }
public void FileDeletedByAnotherProcessAndThenNewFileAppeared() { MockRepository rep = new MockRepository(); IFileSystem fs = rep.CreateMock <IFileSystem>(); // Create and init the first stream long initialSize1 = 100; DateTime modifTime1 = new DateTime(2000, 3, 4); MyFileStream stm1 = rep.CreateMock <MyFileStream>(rep); Expect.Call(stm1.Length).Repeat.Any().Return(initialSize1); Expect.Call(stm1.IsDeleted).Repeat.Any().Return(false); Expect.Call(stm1.LastWriteTime).Repeat.Any().Return(modifTime1); // Instruct file system to return the first stream Expect.Call(fs.OpenFile("test")).Return(stm1); rep.ReplayAll(); using (SimpleFileMedia media = new SimpleFileMedia(fs, SimpleFileMedia.CreateConnectionParamsFromFileName("test"))) { // Check that media refers to the first stream stm1 Assert.AreEqual(initialSize1, media.DataStream.Length); Assert.AreEqual(initialSize1, media.Size); Assert.AreEqual(true, media.IsAvailable); rep.VerifyAll(); rep.BackToRecordAll(); // Simulate file deletion: Length and LastWriteTime keep returning file properties, // but IsDeleted now returns "true". Expect.Call(stm1.Length).Repeat.Any().Return(initialSize1); Expect.Call(stm1.LastWriteTime).Repeat.Any().Return(modifTime1); Expect.Call(stm1.IsDeleted).Repeat.Any().Return(true); // We expect stream stm1 to be released/disposed stm1.Dispose(); LastCall.On(stm1).Repeat.AtLeastOnce(); // Factory cannot open the file that has been deleted while being locked Expect.Call(fs.OpenFile("test")).Repeat.Any().Throw(new UnauthorizedAccessException()); rep.ReplayAll(); // Properties must return previous values as long as Update is not called Assert.AreEqual(initialSize1, media.Size); Assert.AreEqual(initialSize1, media.DataStream.Length); Assert.AreEqual(true, media.IsAvailable); // This update should detect file deletion and release it media.Update(); Assert.AreEqual(0, media.Size); Assert.AreEqual(0, media.DataStream.Length); Assert.AreEqual(false, media.IsAvailable); // Subsequent Updates should change nothing media.Update(); media.Update(); Assert.AreEqual(0, media.Size); Assert.AreEqual(0, media.DataStream.Length); Assert.AreEqual(false, media.IsAvailable); rep.VerifyAll(); rep.BackToRecordAll(); // Simulate that new file with name "test" appeared long initialSize2 = 200; DateTime modifTime2 = new DateTime(2000, 4, 5); MyFileStream stm2 = rep.CreateMock <MyFileStream>(rep); Expect.Call(stm2.Length).Repeat.Any().Return(initialSize2); Expect.Call(stm2.IsDeleted).Repeat.Any().Return(false); Expect.Call(stm2.LastWriteTime).Repeat.Any().Return(modifTime2); stm2.Dispose(); LastCall.On(stm2).Repeat.AtLeastOnce(); Expect.Call(fs.OpenFile("test")).Return(stm2); rep.ReplayAll(); // Properties must return previous values as long as Update is not called Assert.AreEqual(0, media.Size); Assert.AreEqual(0, media.DataStream.Length); Assert.AreEqual(false, media.IsAvailable); // This Update will pick up new file media.Update(); Assert.AreEqual(initialSize2, media.DataStream.Length); Assert.AreEqual(initialSize2, media.Size); Assert.AreEqual(true, media.IsAvailable); // Subsequent Updates should change nothing media.Update(); media.Update(); Assert.AreEqual(initialSize2, media.Size); Assert.AreEqual(initialSize2, media.DataStream.Length); Assert.AreEqual(true, media.IsAvailable); } rep.VerifyAll(); }
public void MediaPropertiesMustChangeOnlyAfterUpdate() { MockRepository rep = new MockRepository(); IFileSystem fs = rep.CreateMock <IFileSystem>(); MyFileStream stm = rep.CreateMock <MyFileStream>(rep); Expect.Call(fs.OpenFile("test")).Return(stm); DateTime time1 = new DateTime(2000, 1, 1); long size1 = 100; Expect.Call(stm.Length).Repeat.Any().Return(size1); Expect.Call(stm.LastWriteTime).Repeat.Any().Return(time1); Expect.Call(stm.IsDeleted).Repeat.Any().Return(false); rep.ReplayAll(); using (SimpleFileMedia media = new SimpleFileMedia(fs, SimpleFileMedia.CreateConnectionParamsFromFileName("test"))) { // Media properties are the same as stm's ones Assert.AreEqual(time1, media.LastModified); Assert.AreEqual(size1, media.Size); rep.VerifyAll(); rep.BackToRecordAll(); // Chnage the properties of stm DateTime time2 = new DateTime(2000, 2, 2); long size2 = 200; Expect.Call(stm.Length).Repeat.Any().Return(size2); Expect.Call(stm.LastWriteTime).Repeat.Any().Return(time2); Expect.Call(stm.IsDeleted).Repeat.Any().Return(false); rep.ReplayAll(); // Properties have not still changed Assert.AreEqual(time1, media.LastModified); Assert.AreEqual(size1, media.Size); // This Update should refresh media's properties media.Update(); Assert.AreEqual(time2, media.LastModified); Assert.AreEqual(size2, media.Size); // Subsequent calls change nothing media.Update(); media.Update(); Assert.AreEqual(time2, media.LastModified); Assert.AreEqual(size2, media.Size); rep.VerifyAll(); rep.BackToRecordAll(); stm.Dispose(); LastCall.On(stm).Repeat.AtLeastOnce(); rep.ReplayAll(); } rep.VerifyAll(); }
public void FileDeletedByAnotherProcessAndThenNewFileAppeared() { IFileSystem fs = Substitute.For <IFileSystem>(); // Create and init the first stream long initialSize1 = 100; DateTime modifTime1 = new DateTime(2000, 3, 4); MyFileStream stm1 = Substitute.For <MyFileStream>(new object()); stm1.Length.Returns(initialSize1); stm1.IsDeleted.Returns(false); stm1.LastWriteTime.Returns(modifTime1); // Instruct file system to return the first stream fs.OpenFile("test").Returns(stm1); MyFileStream stm2 = Substitute.For <MyFileStream>(new object()); using (SimpleFileMedia media = new SimpleFileMedia(fs, SimpleFileMedia.CreateConnectionParamsFromFileName("test"))) { // Check that media refers to the first stream stm1 Assert.AreEqual(initialSize1, media.DataStream.Length); Assert.AreEqual(initialSize1, media.Size); Assert.AreEqual(true, media.IsAvailable); // Simulate file deletion: Length and LastWriteTime keep returning file properties, // but IsDeleted now returns "true". stm1.IsDeleted.Returns(true); // Factory cannot open the file that has been deleted while being locked fs.OpenFile("test").Returns( _ => throw new UnauthorizedAccessException(), _ => throw new UnauthorizedAccessException(), _ => stm2 ); // Properties must return previous values as long as Update is not called Assert.AreEqual(initialSize1, media.Size); Assert.AreEqual(initialSize1, media.DataStream.Length); Assert.AreEqual(true, media.IsAvailable); // This update should detect file deletion and release it media.Update(); Assert.AreEqual(0, media.Size); Assert.AreEqual(0, media.DataStream.Length); Assert.AreEqual(false, media.IsAvailable); stm1.Received(1).Dispose(); // Subsequent Updates should change nothing media.Update(); media.Update(); Assert.AreEqual(0, media.Size); Assert.AreEqual(0, media.DataStream.Length); Assert.AreEqual(false, media.IsAvailable); // Simulate that new file with name "test" appeared long initialSize2 = 200; DateTime modifTime2 = new DateTime(2000, 4, 5); stm2.Length.Returns(initialSize2); stm2.IsDeleted.Returns(false); stm2.LastWriteTime.Returns(modifTime2); // Properties must return previous values as long as Update is not called Assert.AreEqual(0, media.Size); Assert.AreEqual(0, media.DataStream.Length); Assert.AreEqual(false, media.IsAvailable); // This Update will pick up new file media.Update(); Assert.AreEqual(initialSize2, media.DataStream.Length); Assert.AreEqual(initialSize2, media.Size); Assert.AreEqual(true, media.IsAvailable); // Subsequent Updates should change nothing media.Update(); media.Update(); Assert.AreEqual(initialSize2, media.Size); Assert.AreEqual(initialSize2, media.DataStream.Length); Assert.AreEqual(true, media.IsAvailable); } stm2.Received(1).Dispose(); }
public static string ExtractArchive(string resourceFileName) { try { string extractDir = System.IO.Path.GetTempPath(); extractDir = Path.Combine(extractDir, Guid.NewGuid().ToString()); Directory.CreateDirectory(extractDir); string zipFilename = Path.Combine(extractDir, Guid.NewGuid().ToString()); CreateFileFromResource(resourceFileName, zipFilename); ZipInputStream MyZipInputStream = null; FileStream MyFileStream = null; MyZipInputStream = new ZipInputStream(new FileStream(zipFilename, FileMode.Open, FileAccess.Read)); ZipEntry MyZipEntry = MyZipInputStream.GetNextEntry(); Directory.CreateDirectory(extractDir); while (MyZipEntry != null) { if (MyZipEntry.IsDirectory) { Directory.CreateDirectory(extractDir + @"\" + MyZipEntry.Name); } else { if (!Directory.Exists(extractDir + @"\" + Path.GetDirectoryName(MyZipEntry.Name))) { Directory.CreateDirectory(extractDir + @"\" + Path.GetDirectoryName(MyZipEntry.Name)); } MyFileStream = new FileStream(extractDir + @"\" + MyZipEntry.Name, FileMode.OpenOrCreate, FileAccess.Write); int count; byte[] buffer = new byte[4096]; count = MyZipInputStream.Read(buffer, 0, 4096); while (count > 0) { MyFileStream.Write(buffer, 0, count); count = MyZipInputStream.Read(buffer, 0, 4096); } MyFileStream.Close(); } try { MyZipEntry = MyZipInputStream.GetNextEntry(); } catch { MyZipEntry = null; } } if (MyZipInputStream != null) { MyZipInputStream.Close(); } if (MyFileStream != null) { MyFileStream.Close(); } return(extractDir); } catch { throw; } }