Lock() public méthode

public Lock ( long position, long length ) : void
position long
length long
Résultat void
        public FileSystemExclusiveLock(string pathToLock, ILog log)
        {
            EnsureTargetFile(pathToLock, log);

            var success = false;

            //Unfortunately this is the only filesystem locking api that .net exposes
            //You can P/Invoke into better ones but thats not cross-platform
            while (!success)
            {
                try
                {
                    _fileStream = new FileStream(pathToLock, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                    // Oh and there's no async version!
                    _fileStream.Lock(0, 1);
                    success = true;
                }
                catch (IOException)
                {
                    success = false;
                    //Have I mentioned that I hate this algorithm?
                    //This basically just causes the thread to yield to the scheduler
                    //we'll be back here more than 1 tick from now
                    Thread.Sleep(TimeSpan.FromTicks(1));
                }
            }
        }
        public void loadClick(DateTime time)
        {
            // 储存到文件,比如20130203.xml
            string fileName = this.logFile;
            string today = time.ToString("yyyyMMdd");
            SerializableDictionary fileDatas = new SerializableDictionary();

            using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Read))
            {
                stream.Lock(0, stream.Length);
                XmlSerializer serializer = new XmlSerializer(typeof(SerializableDictionary));
                if (stream.Length != 0)
                {
                    fileDatas = (SerializableDictionary)serializer.Deserialize(stream);
                    if (!fileDatas.ContainsKey(today))
                    {
                        fileDatas[today] = new MouseState();
                    }
                }
                else
                {
                    fileDatas = new SerializableDictionary();
                    fileDatas[today] = new MouseState();
                }
                this.leftClickCount = fileDatas[today].leftClickCount;
                this.rightClickCount = fileDatas[today].rightClickCount;
                this.middleClickCount = fileDatas[today].middleClickCount;
            }
        }
Exemple #3
0
        /// <summary>
        /// 写入文本
        /// </summary>
        /// <param name="content">文本内容</param>
        private void Write(string content, string newLine)
        {
            FileInfo fileInfo = new FileInfo(_fileName);

            if (fileInfo.Exists && fileInfo.Length > 1024 * 1000 * 10)
            {
                File.Delete(_fileName);
                Create();
            }

            if (string.IsNullOrEmpty(_fileName))
            {
                throw new Exception("FileName不能为空!");
            }
            using (System.IO.FileStream fs = new System.IO.FileStream(_fileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite, 8, System.IO.FileOptions.Asynchronous))
            {
                //Byte[] dataArray = System.Text.Encoding.ASCII.GetBytes(System.DateTime.Now.ToString() + content + "/r/n");
                Byte[] dataArray = System.Text.Encoding.Default.GetBytes(content + newLine);
                bool   flag      = true;
                long   slen      = dataArray.Length;
                long   len       = 0;
                while (flag)
                {
                    try
                    {
                        if (len >= fs.Length)
                        {
                            fs.Lock(len, slen);
                            lockDic[len] = slen;
                            flag         = false;
                        }
                        else
                        {
                            len = fs.Length;
                        }
                    }
                    catch (Exception ex)
                    {
                        while (!lockDic.ContainsKey(len))
                        {
                            len += lockDic[len];
                        }
                    }
                }
                fs.Seek(len, System.IO.SeekOrigin.Begin);
                fs.Write(dataArray, 0, dataArray.Length);
                fs.Close();
            }
        }
        private static void GetExclusiveAccess(FileStream fs)
        {
            int i;

            for (i = 0; i < 10; i++) {
                try {
                    fs.Lock(0, 1);
                    return;
                } catch {
                    System.Threading.Thread.Sleep(2000);
                }
            }

            throw new Exception("cant get lock for sql recovery on file " + fs.Name);
        }
 static public int Lock(IntPtr l)
 {
     try {
         System.IO.FileStream self = (System.IO.FileStream)checkSelf(l);
         System.Int64         a1;
         checkType(l, 2, out a1);
         System.Int64 a2;
         checkType(l, 3, out a2);
         self.Lock(a1, a2);
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
        public void ExecuteFailsOnException()
        {
            var copyFileAction = new CopyFileAction(Path.Combine(_sourceDirectory, "ExceptionFile.txt"), Path.Combine(_destinationDirectory, "ExceptionFile.txt"));
            using(StreamWriter s = File.CreateText(copyFileAction.Destination))
            {

            }
            using(FileStream fileStream = new FileStream(copyFileAction.Destination, 
                   FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
               {
                   UnicodeEncoding uniEncoding = new UnicodeEncoding();
                   fileStream.Write(uniEncoding.GetBytes("ABC"),0,3);
                   fileStream.Lock(0, 1);
                   Assert.That(copyFileAction.Execute() == false);

               }
            
        }
Exemple #7
0
 private void Write(string content, string newLine)
 {
     if (string.IsNullOrEmpty(FileName))
     {
         throw new Exception("FileName不能为空!");
     }
     using (System.IO.FileStream fs = new System.IO.FileStream(FileName,
                                                               System.IO.FileMode.OpenOrCreate,
                                                               System.IO.FileAccess.ReadWrite,
                                                               System.IO.FileShare.ReadWrite, 8,
                                                               System.IO.FileOptions.Asynchronous))
     {
         Byte[] dataArray = System.Text.Encoding.Default.GetBytes(content + newLine);
         bool   flag      = true;
         long   slen      = dataArray.Length;
         long   len       = 0;
         while (flag)
         {
             try
             {
                 if (len >= fs.Length)
                 {
                     fs.Lock(len, slen);
                     lockDic[len] = slen;
                     flag         = false;
                 }
                 else
                 {
                     len = fs.Length;
                 }
             }
             catch (Exception)
             {
                 while (!lockDic.ContainsKey(len))
                 {
                     len += lockDic[len];
                 }
             }
         }
         fs.Seek(len, System.IO.SeekOrigin.Begin);
         fs.Write(dataArray, 0, dataArray.Length);
         fs.Close();
     }
 }
Exemple #8
0
 private static void Write(string message)
 {
     try
     {
         using (System.IO.FileStream fs = new System.IO.FileStream(ErrorFile, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite, 8, System.IO.FileOptions.Asynchronous))
         {
             Byte[] dataArray = System.Text.Encoding.UTF8.GetBytes("--------start--------" + System.Environment.NewLine + "[" + DateTime.Now.ToString() + "]" + System.Environment.NewLine + message + "---------end---------" + System.Environment.NewLine);
             bool   flag      = true;
             long   slen      = dataArray.Length;
             long   len       = 0;
             while (flag)
             {
                 try
                 {
                     if (len >= fs.Length)
                     {
                         fs.Lock(len, slen);
                         lockDic[len] = slen;
                         flag         = false;
                     }
                     else
                     {
                         len = fs.Length;
                     }
                 }
                 catch (Exception)
                 {
                     while (!lockDic.ContainsKey(len))
                     {
                         len += lockDic[len];
                     }
                 }
             }
             fs.Seek(len, System.IO.SeekOrigin.Begin);
             fs.Write(dataArray, 0, dataArray.Length);
             fs.Close();
         }
     }
     catch
     {
     }
 }
 private static void TryLockFile(FileStream fileStream, long position, long length, int tryCount)
 {
     try
     {
         fileStream.Lock(position, length);
     }
     catch (IOException ex)
     {
         if (!ex.IsLockException())
         {
             throw ex;
         }
         if (tryCount >= 50)
         {
             throw new FileDBException("Database file is in lock for a long time");
         }
         Thread.Sleep((int) (tryCount * 50));
         TryLockFile(fileStream, position, length, ++tryCount);
     }
 }
        private static void TryLockFile(FileStream fileStream, long position, long length, int tryCount)
        {
            try
            {
                fileStream.Lock(position, length);
            }
            catch (IOException ex)
            {
                if (ex.IsLockException())
                {
                    if (tryCount >= DELAY_TRY_LOCK_FILE)
                        throw new FileDBException("Database file is in lock for a long time");

                    Thread.Sleep(tryCount * DELAY_TRY_LOCK_FILE);

                    TryLockFile(fileStream, position, length, ++tryCount);
                }
                else
                    throw ex;
            }
        }
Exemple #11
0
 static bool FileInUse(string path,ref string __message)
 {
     try
     {
         //Just opening the file as open/create
         using (fs = new FileStream(path, FileMode.Open))
         {
             //If required we can check for read/write by using fs.CanRead or fs.CanWrite
             fs.Lock(0, int.MaxValue);
         }
         return false;
     }
     catch (IOException ex)
     {
         //check if message is for a File IO
         __message = ex.Message.ToString();
         if (__message.Contains("The process cannot access the file"))
             return true;
         else
             throw;
     }
 }
Exemple #12
0
 private void LockDataStore(FileStream fs)
 {
     fs.Lock(0, fs.Length);
 }
		// ---------------------------------------------------------------------------

		// No explicit destructors with C#

		// ---------------------------------------------------------------------------

		public bool ReadFromFile(String FileName)
		{
			FileStream fs = null;		
			BinaryReader Source = null;

			bool result = false;  

			try
			{
				// Reset data and search for file tag
				FResetData();
				FID3v1.ReadFromFile(FileName);
				FID3v2.ReadFromFile(FileName);
				FAPEtag.ReadFromFile(FileName);
				// Set read-access, open file and get file length
				fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
				fs.Lock(0,fs.Length);
				Source = new BinaryReader(fs);

				FFileLength = fs.Length;
				// Read header data
				Source.BaseStream.Seek(ID3v2.Size, SeekOrigin.Begin);
    
				//Source.Read(FHeader, sizeof(FHeader));

				FHeader.ID = Source.ReadChars(4);
				FHeader.Size = Source.ReadUInt32();
				FHeader.Length = Source.ReadUInt32();
				FHeader.HiLength = Source.ReadUInt16();
				FHeader.SampleType = Source.ReadByte();
				FHeader.ChannelMode = Source.ReadByte();
				FHeader.SampleRate = Source.ReadInt32();
				FHeader.EncoderID = Source.ReadUInt16();
				FHeader.CompressionID = Source.ReadByte();				

				if ( Utils.StringEqualsArr("OFR ",FHeader.ID) )
					result = true;
			} 
			catch (Exception e) 
			{
				System.Console.WriteLine(e.StackTrace);
				result = false;
			}
			
			if (fs != null)
			{
				fs.Unlock(0,fs.Length);
				if (Source != null) Source.Close();
			}
			return result;
		}
Exemple #14
0
 private FileLock(FileStream fs, string file)
 {
     File = file;
     FileStream = fs;
     FileStream.Lock(0, long.MaxValue);
     Locked = true;
 }
Exemple #15
0
 /// <inheritdoc />
 protected override void OnLockStream(System.IO.FileStream fileStream)
 {
     fileStream.Lock(0, fileStream.Length);
 }
        public int LockFile(String filename, long offset, long length, DokanFileInfo info)
        {
            string path = GetPath(filename);

            try
            {
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);
                fs.Lock(offset, length);
                fs.Close();
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("SetEndOfFile exception: {0}", e.Message);
                return -DokanNet.DOKAN_ERROR;
            }

            return DokanNet.DOKAN_SUCCESS;
        }
Exemple #17
0
		/* -------------------------------------------------------------------------- */

		// No explicit destructors with C#

		/* -------------------------------------------------------------------------- */

		public bool ReadFromFile(String FileName)
		{  
			FileStream fs = null;
			BinaryReader source = null;

			char[] signatureChunk = new char[4];
			tta_header ttaheader = new tta_header();
			long TagSize;

			bool result = false;
  
  
			FResetData();
  
			// load tags first
			FID3v2.ReadFromFile(FileName);
			FID3v1.ReadFromFile(FileName);
			FAPEtag.ReadFromFile(FileName);
  
			// calulate total tag size
			TagSize = 0;
			if (FID3v1.Exists)  TagSize += 128;
			if (FID3v2.Exists)  TagSize += FID3v2.Size;
			if (FAPEtag.Exists)  TagSize += FAPEtag.Size;
  
			// begin reading data from file  
			try
			{
				fs = new FileStream(FileName,FileMode.Open, FileAccess.Read);
				fs.Lock(0,fs.Length);
				source = new BinaryReader(fs);

    	
				// seek past id3v2-tag
				if ( FID3v2.Exists )
				{
					fs.Seek(FID3v2.Size, SeekOrigin.Begin);
				}

				signatureChunk = source.ReadChars(4);
				if ( Utils.StringEqualsArr("TTA1",signatureChunk) ) 
				{    	
					// start looking for chunks
					ttaheader.Reset();
      		
					ttaheader.AudioFormat = source.ReadUInt16();
					ttaheader.NumChannels = source.ReadUInt16();
					ttaheader.BitsPerSample = source.ReadUInt16();
					ttaheader.SampleRate = source.ReadUInt32();
					ttaheader.DataLength = source.ReadUInt32();
					ttaheader.CRC32 = source.ReadUInt32();

					FFileSize = fs.Length;
					FValid = true;

					FAudioFormat = ttaheader.AudioFormat;
					FChannels = ttaheader.NumChannels;
					FBits = ttaheader.BitsPerSample;
					FSampleRate = ttaheader.SampleRate;
					FSamples = ttaheader.DataLength;
					FCRC32 = ttaheader.CRC32;

					FBitrate = (double)FFileSize * 8 / (FSamples / FSampleRate) / 1000;
					FDuration = (double)ttaheader.DataLength / ttaheader.SampleRate;

					result = true;
				}
			} 
			catch (Exception e) 
			{
				System.Console.WriteLine(e.StackTrace);
				result = false;
			}
  
			if (fs != null)  
			{
				fs.Unlock(0,fs.Length);
				if (source != null) source.Close();
			}

  
			return result;
		}
        public override bool Obtain()
        {
            lock (this)
            {
                FailureReason = null;

                if (Channel != null)
                {
                    // Our instance is already locked:
                    return false;
                }

                if (!System.IO.Directory.Exists(LockDir.FullName))
                {
                    try
                    {
                        System.IO.Directory.CreateDirectory(LockDir.FullName);
                    }
                    catch
                    {
                        throw new System.IO.IOException("Cannot create directory: " + LockDir.FullName);
                    }
                }
                else if (File.Exists(LockDir.FullName))
                {
                    throw new IOException("Found regular file where directory expected: " + LockDir.FullName);
                }

                var success = false;
                try
                {
                    Channel = new FileStream(Path.FullName, FileMode.Create, FileAccess.Write, FileShare.None);
                    Channel.Lock(0, Channel.Length);
                    success = true;
                }
                catch (IOException e)
                {
                    FailureReason = e;
                    IOUtils.CloseWhileHandlingException(Channel);
                    Channel = null;
                }
                // LUCENENET: UnauthorizedAccessException does not derive from IOException like in java
                catch (UnauthorizedAccessException e)
                {
                    // On Windows, we can get intermittent "Access
                    // Denied" here.  So, we treat this as failure to
                    // acquire the lock, but, store the reason in case
                    // there is in fact a real error case.
                    FailureReason = e;
                    IOUtils.CloseWhileHandlingException(Channel);
                    Channel = null;
                }
                finally
                {
                    if (!success)
                    {
                        IOUtils.CloseWhileHandlingException(Channel);
                        Channel = null;
                    }
                }

                return Channel != null;
            }
        }
        private void StoreToFile(FileMode fileMode)
        {
            int writeBlock;
            int startIndex;
            const int SEP_LEN = 70;

            writeBlock = this.customInfo.Length + SEP_LEN;
            startIndex = 0;

            FileStream logFileStream = null;
            try
            {
                logFileStream = new FileStream(this.logFilePath, fileMode, FileAccess.Write);

                using (StreamWriter writer = new StreamWriter(logFileStream))
                {
                    logFileStream.Lock(startIndex, writeBlock);
                    writer.BaseStream.Seek(0, SeekOrigin.Current);
                    writer.Write(this.customInfo.ToString());
                    writer.Flush();
                    logFileStream.Unlock(startIndex, writeBlock);
                    logFileStream = null;
                }
            }
            finally
            {
                if (logFileStream != null)
                {
                    logFileStream.Close();
                }
            }
        }
Exemple #20
0
        private void SendGzippedFile(long length, FileStream f, long offset)
        {
            SendUnknownResponseHeader("Content-Encoding", "gzip");
            using (MemoryStream ms = new MemoryStream())
            {
                using (GZipStream gzip = new GZipStream(ms, CompressionMode.Compress))
                {
                    f.Lock(offset, length);
                    f.Seek(offset, SeekOrigin.Begin);
                    const int readBuffLength = 4096;
                    byte[] buffer = new byte[readBuffLength];
                    int readed;
                    while ((readed = f.Read(buffer, 0, readBuffLength)) != 0)
                    {
                        gzip.Write(buffer, 0, readed);
                    }
                    f.Unlock(offset, length);
                    //Write some empty block
                    byte[] rn = Encoding.UTF8.GetBytes(Environment.NewLine);
                    for (int i = 0; i < 3; i++)
                    {
                        gzip.Write(rn, 0, rn.Length);
                    }

                    gzip.Flush();
                    ms.Seek(0, SeekOrigin.Begin);
#if (ETAG)
					FileInfo finfo = new FileInfo(f.Name);
					string etag = string.Format("\"{0}.{1}\"", finfo.LastWriteTimeUtc.ToFileTimeUtc(), ms.Length);
                    SendUnknownResponseHeader("Etag", etag);
#endif
                    SendCalculatedContentLength(ms.Length);
                    SendResponseFromMemoryInternal(ms.GetBuffer(), (int)ms.Length);
                }
            }
        }
Exemple #21
0
		// ---------------------------------------------------------------------------

		private bool ReadData(String FileName, ref FileData Data)
		{ 
			FileStream fs = null;
			BinaryReader Source = null;
			char[] ID = new char[16];
			int ObjectCount;
			int ObjectSize;
			long Position;

			bool result;

			// Read file data
			try
			{
				fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
				fs.Lock(0,fs.Length);
				Source = new BinaryReader(fs);

				Data.FileSize = (int)fs.Length;
    
				// Check for existing header
				ID = Utils.ReadTrueChars(Source,16);

				if ( Utils.ArrEqualsArr(WMA_HEADER_ID,ID) )
				{
					fs.Seek(8, SeekOrigin.Current);
					ObjectCount = Source.ReadInt32();		  
					fs.Seek(2, SeekOrigin.Current);
					// Read all objects in header and get needed data
					for (int iterator=0; iterator<ObjectCount; iterator++)
					{
						Position = fs.Position;
						ID = Utils.ReadTrueChars(Source,16);
						ObjectSize = Source.ReadInt32();			
						ReadObject(ID, Source, ref Data);
						fs.Seek(Position + ObjectSize, SeekOrigin.Begin);				
					}
				}
				result = true;
			} 
			catch (Exception e) 
			{
				System.Console.WriteLine(e.StackTrace);
				//LogDelegator.GetLogDelegate()(Log.LV_ERROR, e.Message);
				result = false;
			}
			if (fs != null)
			{
				fs.Unlock(0,fs.Length);
				fs.Close();
			}
			return result;
		}
        /// <summary>
        /// 写数据
        /// </summary>
        /// <param name="writer">FileStream对象</param>
        /// <param name="data">数据</param>
        /// <returns>true-成功;false-失败</returns>
        private bool Save(FileStream writer, string data)
        {
            if (writer == null || writer.Equals(null))
                return false;

            byte[] b = null;
            long len = 0;

            b = Utf8.GetBytes(data);
            len = writer.Length;
            try
            {
                writer.Lock(0, len);
                writer.Seek(0, SeekOrigin.End);
                writer.Write(b, 0, b.Length);
                writer.Unlock(0, len);
                writer.Flush();
            }
            catch (IOException e)
            {
                throw e;
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
            finally
            {
                try
                {
                    writer.Close();
                }
                catch (Exception Ex)
                {
                    throw Ex;
                }
            }

            return true;
        }
        internal static ResourceDescription ParseResourceDescription(
            string arg,
            string resourceDescriptor,
            string baseDirectory,
            IList<Diagnostic> diagnostics,
            bool embedded)
        {
            string filePath;
            string fullPath;
            string fileName;
            string resourceName;
            string accessibility;

            ParseResourceDescription(
                resourceDescriptor,
                baseDirectory,
                false,
                out filePath,
                out fullPath,
                out fileName,
                out resourceName,
                out accessibility);

            bool isPublic;
            if (accessibility == null)
            {
                // If no accessibility is given, we default to "public".
                // NOTE: Dev10 distinguishes between null and empty/whitespace-only.
                isPublic = true;
            }
            else if (string.Equals(accessibility, "public", StringComparison.OrdinalIgnoreCase))
            {
                isPublic = true;
            }
            else if (string.Equals(accessibility, "private", StringComparison.OrdinalIgnoreCase))
            {
                isPublic = false;
            }
            else
            {
                AddDiagnostic(diagnostics, ErrorCode.ERR_BadResourceVis, accessibility);
                return null;
            }

            if (string.IsNullOrEmpty(filePath))
            {
                AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
                return null;
            }

            if (fullPath == null || string.IsNullOrWhiteSpace(fileName) || fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
            {
                AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, filePath);
                return null;
            }

            Func<Stream> dataProvider = () =>
                                            {
                                                // Use FileShare.ReadWrite because the file could be opened by the current process.
                                                // For example, it is an XML doc file produced by the build.
                                                var stream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                                                // Lock the entire content to prevent others from modifying it while we are reading.
                                                try
                                                {
                                                    stream.Lock(0, long.MaxValue);
                                                    return stream;
                                                }
                                                catch
                                                {
                                                    stream.Dispose();
                                                    throw;
                                                }
                                            };
            return new ResourceDescription(resourceName, fileName, dataProvider, isPublic, embedded, checkArgs: false);
        }
Exemple #24
0
		public void TestLock ()
		{
			string path = TempFolder + Path.DirectorySeparatorChar + "TestLock";
			DeleteFile (path);

			FileStream stream = new FileStream (path, FileMode.CreateNew, FileAccess.ReadWrite);

			stream.Write (new Byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 0, 10);
			stream.Close ();

			stream = new FileStream (path, FileMode.Open, FileAccess.ReadWrite);

			stream.Lock (0, 5);

			FileStream stream2 = new FileStream (path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

			byte[] bytes = new byte[5];
			try {
				stream2.Read (bytes, 0, 5);
				Assert.Fail ("#A1");
			} catch (Exception) {
				// Bug #71371: on MS.NET you get an IOException detailing a lock
				// Assert.AreEqual (typeof (IOException), e.GetType (), "#A2");
			}

			stream2.Seek (5, SeekOrigin.Begin);
			stream2.Read (bytes, 0, 5);

			Assert.AreEqual (5, bytes[0], "#B1");
			Assert.AreEqual (6, bytes[1], "#B2");
			Assert.AreEqual (7, bytes[2], "#B3");
			Assert.AreEqual (8, bytes[3], "#B4");
			Assert.AreEqual (9, bytes[4], "#B5");

			stream.Unlock (0, 5);
			stream2.Seek (0, SeekOrigin.Begin);
			stream2.Read (bytes, 0, 5);

			Assert.AreEqual (0, bytes[0], "#C1");
			Assert.AreEqual (1, bytes[1], "#C2");
			Assert.AreEqual (2, bytes[2], "#C3");
			Assert.AreEqual (3, bytes[3], "#C4");
			Assert.AreEqual (4, bytes[4], "#C5");

			stream.Close ();
			stream2.Close ();

			DeleteFile (path);
		}
		// Bug: 71371 -> duplicate and WONTFIX.
		public void TestLock_FailsOnMono ()
		{
			string path = TempFolder + Path.DirectorySeparatorChar + "TestLock";
                	DeleteFile (path);

                	FileStream stream = new FileStream (path, FileMode.CreateNew, FileAccess.ReadWrite);
                	                	
	               	stream.Write (new Byte [] {0,1,2,3,4,5,6,7,8,9,10}, 0, 10);                              	
                	stream.Close ();

                	stream = new FileStream (path, FileMode.Open, FileAccess.ReadWrite);
                	
                	stream.Lock (0, 5);
                	
                	FileStream stream2 = new FileStream (path , FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                	
                	byte [] bytes = new byte [5];
                	try {                		
                		stream2.Read (bytes, 0, 5);
                		Fail ();
                	} catch (Exception e) {
                		
                		// locked
                		AssertEquals ("test#01", typeof (IOException), e.GetType ());
                	}

					stream.Close ();
                	stream2.Close ();
                	
                	DeleteFile (path);                		
		}
Exemple #26
0
		// ---------------------------------------------------------------------------

		// No explicit destructors in C#

		// ---------------------------------------------------------------------------

		public bool ReadFromFile(String FileName)
		{
   
			APE_HEADER APE = new APE_HEADER();				// common header
			APE_HEADER_OLD APE_OLD = new APE_HEADER_OLD();	// old header   <= 3.97
			APE_HEADER_NEW APE_NEW = new APE_HEADER_NEW();	// new header   >= 3.98
			APE_DESCRIPTOR APE_DESC = new APE_DESCRIPTOR(); // extra header >= 3.98

			FileStream fs = null;
			BinaryReader SourceFile = null;

			int BlocksPerFrame;
			bool LoadSuccess;
			int TagSize;
			bool result = false;
   
			FResetData();
   
			// load tags first
			FID3v2.ReadFromFile(FileName);
			FID3v1.ReadFromFile(FileName);
			FAPEtag.ReadFromFile(FileName);
   
			// calculate total tag size
			TagSize = 0;
			if (FID3v1.Exists) TagSize += 128;
			if (FID3v2.Exists) TagSize += FID3v2.Size;
			if (FAPEtag.Exists) TagSize += FAPEtag.Size;
   
			// reading data from file
			LoadSuccess = false;

			try
			{
				try
				{         
					fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
					fs.Lock(0,fs.Length);
					SourceFile = new BinaryReader(fs);
					FFileSize = fs.Length;

					// seek past id3v2-tag
					if (FID3v2.Exists)
					{
						fs.Seek(FID3v2.Size, SeekOrigin.Begin);
					}
					// Read APE Format Header         
					Array.Clear(APE.cID,0,APE.cID.Length);
					APE.nVersion = 0;
	  
					APE.cID = SourceFile.ReadChars(4);
					APE.nVersion = SourceFile.ReadUInt16();

					if ( Utils.StringEqualsArr("MAC ",APE.cID) )
					{            
						FVersion = APE.nVersion;

						FVersionStr = ((double)FVersion / 1000).ToString().Substring(0,4); //Str(FVersion / 1000 : 4 : 2, FVersionStr);
            
						// Load New Monkey's Audio Header for version >= 3.98
						if (APE.nVersion >= 3980) 
						{
							APE_DESC.padded = 0;
							APE_DESC.nDescriptorBytes = 0;
							APE_DESC.nHeaderBytes = 0;
							APE_DESC.nSeekTableBytes = 0;
							APE_DESC.nHeaderDataBytes = 0;
							APE_DESC.nAPEFrameDataBytes = 0;
							APE_DESC.nAPEFrameDataBytesHigh = 0;
							APE_DESC.nTerminatingDataBytes = 0;
							Array.Clear(APE_DESC.cFileMD5,0,APE_DESC.cFileMD5.Length);

							APE_DESC.padded = SourceFile.ReadUInt16();
							APE_DESC.nDescriptorBytes = SourceFile.ReadUInt32();
							APE_DESC.nHeaderBytes = SourceFile.ReadUInt32();
							APE_DESC.nSeekTableBytes = SourceFile.ReadUInt32();
							APE_DESC.nHeaderDataBytes = SourceFile.ReadUInt32();
							APE_DESC.nAPEFrameDataBytes = SourceFile.ReadUInt32();
							APE_DESC.nAPEFrameDataBytesHigh = SourceFile.ReadUInt32();
							APE_DESC.nTerminatingDataBytes = SourceFile.ReadUInt32();
							APE_DESC.cFileMD5 = SourceFile.ReadBytes(16);

							// seek past description header
							if (APE_DESC.nDescriptorBytes != 52) fs.Seek(APE_DESC.nDescriptorBytes - 52, SeekOrigin.Current);
							// load new ape_header
							if (APE_DESC.nHeaderBytes > 24/*sizeof(APE_NEW)*/) APE_DESC.nHeaderBytes = 24/*sizeof(APE_NEW)*/;
                  				
							APE_NEW.nCompressionLevel = 0;
							APE_NEW.nFormatFlags = 0;
							APE_NEW.nBlocksPerFrame = 0;
							APE_NEW.nFinalFrameBlocks = 0;
							APE_NEW.nTotalFrames = 0;
							APE_NEW.nBitsPerSample = 0;
							APE_NEW.nChannels = 0;
							APE_NEW.nSampleRate = 0;

							APE_NEW.nCompressionLevel = SourceFile.ReadUInt16();
							APE_NEW.nFormatFlags = SourceFile.ReadUInt16();
							APE_NEW.nBlocksPerFrame = SourceFile.ReadUInt32();
							APE_NEW.nFinalFrameBlocks = SourceFile.ReadUInt32();
							APE_NEW.nTotalFrames = SourceFile.ReadUInt32();
							APE_NEW.nBitsPerSample = SourceFile.ReadUInt16();
							APE_NEW.nChannels = SourceFile.ReadUInt16();
							APE_NEW.nSampleRate = SourceFile.ReadUInt32();
				
							// based on MAC SDK 3.98a1 (APEinfo.h)
							FSampleRate       = (int)APE_NEW.nSampleRate;
							FChannels         = APE_NEW.nChannels;
							FFormatFlags      = APE_NEW.nFormatFlags;
							FBits             = APE_NEW.nBitsPerSample;
							FCompressionMode  = APE_NEW.nCompressionLevel;
							// calculate total uncompressed samples
							if (APE_NEW.nTotalFrames > 0)
							{
								FTotalSamples     = (long)(APE_NEW.nBlocksPerFrame) *
									(long)(APE_NEW.nTotalFrames-1) +
									(long)(APE_NEW.nFinalFrameBlocks);
							}
							LoadSuccess = true;
						}
						else 
						{
							// Old Monkey <= 3.97               

							APE_OLD.nCompressionLevel = 0;
							APE_OLD.nFormatFlags = 0;
							APE_OLD.nChannels = 0;
							APE_OLD.nSampleRate = 0;
							APE_OLD.nHeaderBytes = 0;
							APE_OLD.nTerminatingBytes = 0;
							APE_OLD.nTotalFrames = 0;
							APE_OLD.nFinalFrameBlocks = 0;
							APE_OLD.nInt = 0;

							APE_OLD.nCompressionLevel = SourceFile.ReadUInt16();
							APE_OLD.nFormatFlags = SourceFile.ReadUInt16();
							APE_OLD.nChannels = SourceFile.ReadUInt16();
							APE_OLD.nSampleRate = SourceFile.ReadUInt32();
							APE_OLD.nHeaderBytes = SourceFile.ReadUInt32();
							APE_OLD.nTerminatingBytes = SourceFile.ReadUInt32();
							APE_OLD.nTotalFrames = SourceFile.ReadUInt32();
							APE_OLD.nFinalFrameBlocks = SourceFile.ReadUInt32();
							APE_OLD.nInt = SourceFile.ReadInt32();				

							FCompressionMode  = APE_OLD.nCompressionLevel;
							FSampleRate       = (int)APE_OLD.nSampleRate;
							FChannels         = APE_OLD.nChannels;
							FFormatFlags      = APE_OLD.nFormatFlags;
							FBits = 16;
							if ( (APE_OLD.nFormatFlags & MONKEY_FLAG_8_BIT ) != 0) FBits =  8;
							if ( (APE_OLD.nFormatFlags & MONKEY_FLAG_24_BIT) != 0) FBits = 24;

							FHasSeekElements  = ( (APE_OLD.nFormatFlags & MONKEY_FLAG_PEAK_LEVEL   )  != 0);
							FWavNotStored     = ( (APE_OLD.nFormatFlags & MONKEY_FLAG_SEEK_ELEMENTS) != 0);
							FHasPeakLevel     = ( (APE_OLD.nFormatFlags & MONKEY_FLAG_WAV_NOT_STORED) != 0);
                  
							if (FHasPeakLevel)
							{
								FPeakLevel        = (uint)APE_OLD.nInt;
								FPeakLevelRatio   = (FPeakLevel / (1 << FBits) / 2.0) * 100.0;
							}

							// based on MAC_SDK_397 (APEinfo.cpp)
							if (FVersion >= 3950) 
								BlocksPerFrame = 73728 * 4;
							else if ( (FVersion >= 3900) || ((FVersion >= 3800) && (MONKEY_COMPRESSION_EXTRA_HIGH == APE_OLD.nCompressionLevel)) )
								BlocksPerFrame = 73728;
							else
								BlocksPerFrame = 9216;

							// calculate total uncompressed samples
							if (APE_OLD.nTotalFrames>0)
							{
								FTotalSamples =  (long)(APE_OLD.nTotalFrames-1) *
									(long)(BlocksPerFrame) +
									(long)(APE_OLD.nFinalFrameBlocks);
							}
							LoadSuccess = true;
               
						}
						if (LoadSuccess) 
						{
							// compression profile name
							if ( (0 == (FCompressionMode % 1000)) && (FCompressionMode<=6000) )
							{
								FCompressionModeStr = MONKEY_COMPRESSION[FCompressionMode / 1000]; // int division
							}
							else 
							{
								FCompressionModeStr = FCompressionMode.ToString();
							}
							// length
							if (FSampleRate>0) FDuration = ((double)FTotalSamples / FSampleRate);
							// average bitrate
							if (FDuration>0) FBitrate = 8*(FFileSize - (long)(TagSize)) / (FDuration*1000);
							// some extra sanity checks
							FValid   = ((FBits>0) && (FSampleRate>0) && (FTotalSamples>0) && (FChannels>0));
							result   = FValid;
						}
					}
				}
				finally
				{
					if (fs != null)
					{
						fs.Unlock(0,fs.Length);
						if (SourceFile != null) SourceFile.Close();
					}
				}
			}
			catch (Exception e)
			{
				System.Console.WriteLine(e.StackTrace);
				result = false;
			}
			return result;
		}
Exemple #27
0
        public override void Process()
        {
            // save the List.xml in [temp-directory]\List\List_[SenderID].xml
            while (true)
            {
                try
                {
                    FileStream fs = new FileStream((Global.TempDirectory + @"\List\" + string.Format("List_{0}.xml", this.SenderPeer.ID)), FileMode.Create);

                    try { fs.Lock(0, fs.Length); }
                    catch { }

                    fs.Write(m_bytXmlBinary, 0, m_bytXmlBinary.Length);

                    try { fs.Unlock(0, fs.Length); }
                    catch { }

                    fs.Close();

                    break;
                }

                catch
                {
                    Thread.Sleep(1);
                }
            }
        }
Exemple #28
0
        // DonwFile-返回包处理
        private void udpProDownFileBack(UnUdpEntity etBack)
        {
            // 刷新超时时间戳
            timeOutTicks = UnDate.ticksMSec();
            switch (etBack.Event.getUnUdpEveEnum())
            {
                case UnUdpEveEnum.downFileQueryBack:
                    sleepTime = Convert.ToInt32(UnDate.ticksMSec() - traTicks) + 1;
                    if (sleepTime > 10000)
                    {
                        sleepTime = 2000;
                    }
                    // 初始化
                    FileInfo cofFi = new FileInfo(UnUdpHelp.getDownFileTmpConfigPath(etBack.HashCode));
                    FileInfo tmpFi = new FileInfo(UnUdpHelp.getDownFileReceivePath(etBack.HashCode));
                    if (!cofFi.Exists)
                    {
                        DirectoryInfo di = new DirectoryInfo(UnUdpHelp.getDownFileTmpDirectory(etBack.HashCode));
                        if (!di.Exists)
                        {
                            di.Create();
                        }
                        cofFi.Create().Dispose();
                        tmpFi.Create().Dispose();
                        downQuery = etBack;
                    }

                    // 第一次初始化
                    if (downQuery.TotalPacks == 0)
                    {
                        // 获得配置文件
                        using (FileStream fs = cofFi.OpenRead())
                        {
                            byte[] b = new byte[fs.Length];
                            fs.Read(b, 0, b.Length);
                            downQuery = UnUdpHelp.analyzePackage(b);
                        }
                    }
                    else
                    {
                        downQuery.IntMin = etBack.IntMin;
                        downQuery.IntMax = etBack.IntMax;
                    }

                    // 写入配置文件
                    using (FileStream fs = new FileStream(UnUdpHelp.getDownFileTmpConfigPath(etBack.HashCode), FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        byte[] prgBackBts = UnUdpHelp.assemblePackage(downQuery);
                        fs.SetLength(0);
                        fs.Seek(0, SeekOrigin.Begin);
                        fs.Write(prgBackBts, 0, prgBackBts.Length);
                    }

                    // 建立窗口
                    downIntervals = new List<UnUdpEntity>();
                    for (long i = downQuery.IntMin; i <= downQuery.IntMax; i++)
                    {
                        UnUdpEntity uup = new UnUdpEntity();
                        uup.PackNo = i;
                        upp.isSend = false;
                        downIntervals.Add(uup);
                    }
                    isdbPer = true;
                    break;
                case UnUdpEveEnum.downFileBack:
                    UnUdpEntity up = downIntervals.Find(t => t.PackNo == etBack.PackNo && t.isSend == false);
                    string tmpPath = UnUdpHelp.getDownFileReceivePath(downQuery.HashCode);
                    if (up != null)
                    {
                        // 写入数据
                        using (FileStream fs = new FileStream(tmpPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            fs.Lock(etBack.PackOffset, etBack.PackData.Length);
                            fs.Seek(etBack.PackOffset, SeekOrigin.Begin);
                            fs.Write(etBack.PackData, 0, etBack.PackData.Length);
                            fs.Unlock(etBack.PackOffset, etBack.PackData.Length);
                            downQuery.UpCount++;
                            up.isSend = true;
                        }
                        udpAddDownProgress(downQuery);
                    }
                    // 下载完成
                    if (downQuery.UpCount == downQuery.TotalPacks)
                    {
                        _isFinish = true;
                        // 转正式文件
                        string newPath = UnUdpHelp.getDownFileSavePath(downQuery.HashCode, downQuery.Extent);
                        UnFile.move(tmpPath, newPath, true);
                        // 删除临时文件夹
                        File.Delete(UnUdpHelp.getDownFileTmpConfigPath(downQuery.HashCode));
                        Directory.Delete(UnUdpHelp.getDownFileTmpDirectory(downQuery.HashCode));
                        if (intTransfer != null)
                        {
                            UnAttrRst rst = new UnAttrRst();
                            rst.pid = _pid;
                            rst.code = 1;
                            rst.msg = "下载完成";
                            rst.back = newPath;
                            intTransfer.success(rst);
                        }
                    }
                    break;
            }
        }
Exemple #29
0
        /// <summary>
        /// Causes a thread to be scheduled for execution.
        /// </summary>
        protected override void ExecuteTask()
        {
            string ver = SharpPcap.Version.VersionString;

            // Get the local processing folders
            DirectoryInfo captureDir = new DirectoryInfo(_captureToFolder);
            DirectoryInfo processDir = new DirectoryInfo(_processToFolder);
            DirectoryInfo outputDir = new DirectoryInfo(_statisticsToFolder);

            // Get the local drive for checking disk space
            DriveInfo volume = new DriveInfo(outputDir.Root.ToString());

            FileInfo pcapFile = null;
            string pcapFilename = "";
            string pcapFilter = "*.pcap";

            DateTime start = DateTime.Now;

            do
            {
                //Check if there are files if not wait 10 sec then check again
                do
                {
                    TimeSpan timer = DateTime.Now - start;
                    int seconds = (int)timer.TotalSeconds;
                    Console.WriteLine("-> {0} seconds to process.", seconds.ToString());
                    start = DateTime.Now;

                    // Null the file until we find one that is unlocked
                    pcapFile = null;
                    try
                    {
                        foreach (FileInfo p in captureDir.GetFiles(pcapFilter))
                        {
                            Console.WriteLine(p.FullName);

                            if (!this.Running) { break; }

                            // Check to see if the file is locked using a file stream and FileShare.None
                            // If the file is not locked, keep it locked for at least a second

                            FileStream fs = new FileStream(p.FullName, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
                            fs.Lock(0, fs.Length);
                            System.Threading.Thread.Sleep(1000);

                            // Get the file a
                            pcapFile = p;
                            pcapFilename = processDir.FullName + "\\" + pcapFile.Name;
                            long NeededSpace = p.Length * 2; // Double for enough free space for one capture with room remaining

                            // Unlock and close
                            fs.Unlock(0, fs.Length);
                            fs.Close();

                            // Check available disk space
                            if (NeededSpace > volume.AvailableFreeSpace)
                            {
                                this.parentService.Log(EventLogEntryType.Error, 1, "The disk drive " + outputDir.Root.ToString() + " is too low on disk space to analyze packet capture statistics.");
                                this.parentService.Stop();
                                return;
                            }

                            // Move the file for processing
                            pcapFile.MoveTo(pcapFilename);
                            break;
                        }
                    }
                    catch (System.IO.IOException)
                    {
                        // The file selected is locked by another thread or process
                        pcapFile = null;
                    }
                    catch (Exception ex)
                    {
                        // Log any errors
                        this.parentService.Log(EventLogEntryType.Warning,
                            "{0} thread ({1}) error opening pcap file.\n{2}",
                            this.ThreadName,
                            this.ThreadId.ToString(),
                            ex.ToString());

                        pcapFile = null;
                    }

                    // If we have gotten this far, then no files are available or all files are locked
                    // Sleep the thread
                    if (!(pcapFile == null))
                        System.Threading.Thread.Sleep(10000);

                } while (pcapFile == null);

                parsePcap(pcapFilename, outputDir);

            } while (this.Running);

            // End the thread and return
            this.Stop();
        }
        public void Create_ZipErrorAction_Skip()
        {
            Directory.SetCurrentDirectory(TopLevelDir);
            string dirToZip = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
            var files = TestUtilities.GenerateFilesFlat(dirToZip);

            // m is the number of files to lock
            for (int m = 1; m < 4; m++)
            {
                // k is the type of locking.  0 == whole file, 1 == range lock
                for (int k = 0; k < 2; k++)
                {
                    TestContext.WriteLine("Trial {0}.{1}...", m, k);
                    string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("Create_ZipErrorAction_Skip-{0}-{1}.zip", m, k));
                    var locked = new Dictionary<String, FileStream>();
                    try
                    {
                        for (int i = 0; i < m; i++)
                        {
                            int n = 0;
                            do
                            {
                                n = _rnd.Next(files.Length);
                            } while (locked.ContainsKey(files[n]));

                            TestContext.WriteLine("  Locking file {0}...", files[n]);

                            FileStream lockStream = null;
                            if (k == 0)
                            {
                                lockStream = new FileStream(files[n], FileMode.Open, FileAccess.Read, FileShare.None);
                            }
                            else
                            {
                                lockStream = new FileStream(files[n], FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                                int r = _rnd.Next((int)(lockStream.Length / 2));
                                int s = _rnd.Next((int)(lockStream.Length / 2));
                                lockStream.Lock(s, r);
                            }

                            locked.Add(files[n], lockStream);
                        }

                        using (var zip = new ZipFile())
                        {
                            zip.ZipErrorAction = ZipErrorAction.Skip;
                            zip.AddFiles(files, "fodder");
                            zip.Save(zipFileToCreate);
                        }

                        using (var zip = FileSystemZip.Read(zipFileToCreate))
                        {
                            // Writing the info as a single block puts everything on the
                            // same line, makes it unreadable.  So we split the strings on
                            // newline boundaries and write them individually.
                            foreach (string s in zip.Info.Split('\r', '\n'))
                            {
                                Console.WriteLine("{0}", s);
                            }
                        }

                        BasicVerifyZip(zipFileToCreate);

                        Assert.AreEqual<int>(files.Length - m, TestUtilities.CountEntries(zipFileToCreate),
                                             "The zip file created has the wrong number of entries.");
                    }
                    finally
                    {
                        foreach (String s in locked.Keys)
                        {
                            locked[s].Close();
                        }
                    }

                    TestContext.WriteLine("  ...");
                    System.Threading.Thread.Sleep(320);
                }
            }
        }
Exemple #31
0
		/* -------------------------------------------------------------------------- */

		public bool GetInfo( String sFile, bool bSetTags)
		{
			FileStream fs = null;
			BinaryReader r = null;

			byte[] aMetaDataBlockHeader = new byte[4];
			int iBlockLength;
			int iMetaType;
			int iIndex;
			bool bPaddingFound;

			bool result = true;
  
			bPaddingFound = false;
			FResetData( true, false );
  
			try
			{
				// Read data from ID3 tags
				FID3v2.ReadFromFile(sFile);

				// Set read-access and open file
				fs = new FileStream(sFile,FileMode.Open, FileAccess.Read);
				fs.Lock(0,fs.Length);
				r = new BinaryReader(fs);

				FFileLength = (int)fs.Length;
				FFileName = sFile;

				// Seek past the ID3v2 tag, if there is one
				if (FID3v2.Exists)  
				{
					fs.Seek(FID3v2.Size, SeekOrigin.Begin);
				}

				// Read header data    
				FHeader.Reset();
    
				FHeader.StreamMarker = r.ReadChars(4);
				FHeader.MetaDataBlockHeader = r.ReadBytes(4);
				FHeader.Info = r.ReadBytes(18);
				FHeader.MD5Sum = r.ReadBytes(16);

				// Process data if loaded and header valid    
				if ( Utils.StringEqualsArr("fLaC",FHeader.StreamMarker) )
				{
					FChannels      = (byte)( ((FHeader.Info[12] >> 1) & 0x7) + 1 );
					FSampleRate    = ( FHeader.Info[10] << 12 | FHeader.Info[11] << 4 | FHeader.Info[12] >> 4 );
					FBitsPerSample = (byte)( ((FHeader.Info[12] & 1) << 4) | (FHeader.Info[13] >> 4) + 1 );
					FSamples       = ( FHeader.Info[14] << 24 | FHeader.Info[15] << 16 | FHeader.Info[16] << 8 | FHeader.Info[17] );

					if ( 0 == (FHeader.MetaDataBlockHeader[1] & 0x80) ) // metadata block exists
					{
						iIndex = 0;
						do // read more metadata blocks if available
						{		  
							aMetaDataBlockHeader = r.ReadBytes(4);

							iIndex++; // metadatablock index
							iBlockLength = (aMetaDataBlockHeader[1] << 16 | aMetaDataBlockHeader[2] << 8 | aMetaDataBlockHeader[3]); //decode length
							if (iBlockLength <= 0) break; // can it be 0 ?

							iMetaType = (aMetaDataBlockHeader[0] & 0x7F); // decode metablock type

							if ( iMetaType == META_VORBIS_COMMENT )
							{  // read vorbis block
								FVCOffset = (int)fs.Position;
								FTagSize = iBlockLength;
								FVorbisIndex = iIndex;
								ReadTag(r, bSetTags); // set up fields
							}
							else 
							{
								if ((iMetaType == META_PADDING) && (! bPaddingFound) )  // we have padding block
								{ 
									FPadding = iBlockLength;                                            // if we find more skip & put them in metablock array
									FPaddingLast = ((aMetaDataBlockHeader[0] & 0x80) != 0);
									FPaddingIndex = iIndex;
									bPaddingFound = true;
									fs.Seek(FPadding, SeekOrigin.Current); // advance into file till next block or audio data start
								} 
								else // all other
								{ 
									if (iMetaType <= 5)   // is it a valid metablock ?
									{ 
										if (META_PADDING == iMetaType)  // set flag for fragmented padding blocks
										{ 
											FPaddingFragments = true;
										}
										AddMetaDataOther(aMetaDataBlockHeader, r, iBlockLength, iIndex);
									} 
									else 
									{
										FSamples = 0; //ops...
										break;
									}
								}
							}
						}
						while ( 0 == (aMetaDataBlockHeader[0] & 0x80) ); // while is not last flag ( first bit == 1 )
					}
				}
			} 
			catch (Exception e) 
			{
				System.Console.WriteLine(e.StackTrace);
				//LogDelegator.GetLogDelegate()(Log.LV_ERROR,e.Message);
				result = false;
			}
    
			if (FIsValid())  
			{
				FAudioOffset = (int)fs.Position;  // we need that to rebuild the file if nedeed
				FBitrate = Math.Round( ( (double)( FFileLength - FAudioOffset ) / 1000 ) * 8 / FGetDuration() ); //time to calculate average bitrate
			} 
			else 
			{
				result = false;
			}
    
			if (fs != null)  
			{
				fs.Unlock(0,fs.Length);
				fs.Close();
			}

			return result;  
		}
		public void Lock_Disposed () 
		{
			string path = TempFolder + Path.DirectorySeparatorChar + "temp";
			DeleteFile (path);
			FileStream stream = new FileStream (path, FileMode.OpenOrCreate, FileAccess.Write);
			stream.Close ();
			stream.Lock (0,1);
		}
Exemple #33
0
		// ---------------------------------------------------------------------------

		bool AddToFile(String FileName, Stream TagData)
		{
			FileStream fs = null;
			BinaryWriter TargetFile = null;
			bool result;

			try
			{
				// Add tag data to file
				fs = new FileStream(FileName, FileMode.Open, FileAccess.Write);
				fs.Lock(0,fs.Length); // Share Exclusive - originally, read denied
				TargetFile = new BinaryWriter(fs);

				TargetFile.BaseStream.Seek(0, SeekOrigin.End);
				TagData.Seek(0, SeekOrigin.Begin);
			
				byte[] bytes = new byte[TagData.Length];
				int numBytesToRead = (int) TagData.Length;
				int numBytesRead = 0;
				while (numBytesToRead > 0) 
				{
					// Read may return anything from 0 to numBytesToRead.
					int n = TagData.Read(bytes, numBytesRead, numBytesToRead);
					TargetFile.Write(bytes,0,n);

					// The end of the file is reached.
					if (0==n) break;
					numBytesRead += n;
					numBytesToRead -= n;				
				}
				//TargetFile.Write(TagData.ReadChars(TagData.Length));
				//FileData.CopyFrom(TagData, TagData.Size);
										
				result = true;
			} 
			catch (Exception e)
			{
				System.Console.WriteLine(e.StackTrace);
				result = false;
			}
			if (fs != null)
			{
				fs.Unlock(0,fs.Length);
				if (TargetFile != null) TargetFile.Close();
			}

			return result;
		}
                public void TestLock()
                {
			string path = TempFolder + Path.DirectorySeparatorChar + "TestLock";
                	DeleteFile (path);

                	FileStream stream = new FileStream (path, FileMode.CreateNew, FileAccess.ReadWrite);
                	                	
	               	stream.Write (new Byte [] {0,1,2,3,4,5,6,7,8,9,10}, 0, 10);                              	
                	stream.Close ();

                	stream = new FileStream (path, FileMode.Open, FileAccess.ReadWrite);
                	
                	stream.Lock (0, 5);
                	
                	FileStream stream2 = new FileStream (path , FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                	
                	byte [] bytes = new byte [5];
                	try {                		
                		stream2.Read (bytes, 0, 5);
                		Fail ();
                	} catch (Exception e) {
                		
                		// locked
                		// AssertEquals ("test#01", typeof (IOException), e.GetType ());
				//
				// Moved into the previous test case.
                	}
               		                
                	stream2.Seek (5, SeekOrigin.Begin);
               		stream2.Read (bytes, 0, 5);
                	
                	AssertEquals ("test#02", 5, bytes [0]);
                	AssertEquals ("test#03", 6, bytes [1]);                	
                	AssertEquals ("test#04", 7, bytes [2]); 
                	AssertEquals ("test#05", 8, bytes [3]);
                	AssertEquals ("test#06", 9, bytes [4]);
                	
                	stream.Unlock (0,5);
                	stream2.Seek (0, SeekOrigin.Begin);	
               		stream2.Read (bytes, 0, 5);
                	
                	AssertEquals ("test#02", 0, bytes [0]);
                	AssertEquals ("test#03", 1, bytes [1]);                	
                	AssertEquals ("test#04", 2, bytes [2]); 
                	AssertEquals ("test#05", 3, bytes [3]);
                	AssertEquals ("test#06", 4, bytes [4]);
                	                	
                	stream.Close ();
                	stream2.Close ();
                	
                	DeleteFile (path);                		
                }
        /// <summary>
        /// Starts the journal system.
        /// </summary>
        internal void Start()
        {
            lock_file = new FileStream(Path.Combine(journal_path, "lock.m"), FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None);
            lock_file.Lock(0, lock_file.Length);

            if (ENABLE_LOGGING) {
                lock (init_lock) {
                    if (journaling_thread == null) {
                        // Start the background journaling thread,
                        journaling_thread = new JournalingThread(this);
                        journaling_thread.Start();
                        // Scan for any changes and make the changes.
                        RollForwardRecover();
                        if (!read_only) {
                            // Create a new top journal file
                            NewTopJournalFile();
                        }
                    } else {
                        throw new ApplicationException("Assertion failed - already started.");
                    }
                }
            }
        }