Exemplo n.º 1
0
 public FileLock lockJ(long position, long size, bool shared)
 {
     try {
         delegateInstance.Lock(position, size);                  // Works it?
         this.fileLock = new FileLock(this, position, size, shared);
         return(this.fileLock);
     }
     catch (System.Exception ex) {
         throw new java.io.IOException(ex.getMessage());
     }
 }
Exemplo n.º 2
0
        /// <summary>
        /// 写入文本
        /// </summary>
        /// <param name="content">文本内容</param>
        private void Write(string content, string newLine)
        {
            if (string.IsNullOrEmpty(_fileName))
            {
                return;
                //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.UTF8.GetBytes(content + newLine);
                bool   flag      = true;
                long   slen      = dataArray.Length;
                long   len       = 0;
                lock (_lock)
                {
                    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();
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// 写入文本
        /// </summary>
        /// <param name="content">文本内容</param>
        private static void Write(string content, string newLine)
        {
            var fileName = GetFileName();

            Create(fileName);

            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 ex)
                    {
                        while (!lockDic.ContainsKey(len))
                        {
                            len += lockDic[len];
                        }
                    }
                }
                fs.Seek(len, System.IO.SeekOrigin.Begin);
                fs.Write(dataArray, 0, dataArray.Length);
                fs.Close();
            }
        }
Exemplo n.º 4
0
 public void SaveLogToFile()
 {
     try
     {
         string logInfo = GetLogText();
         if (logInfo.Length > 0)
         {
             System.IO.FileStream fs = GetFileStream();
             byte[] buffer           = System.Text.UTF8Encoding.UTF8.GetBytes(logInfo);
             long   lockBegin        = fs.Length;
             long   lockEnd          = buffer.Length;
             fs.Position = lockBegin;
             fs.Lock(lockBegin, lockEnd);
             //fs.WriteAsync(buffer, 0, buffer.Length);
             fs.Write(buffer, 0, buffer.Length);
             fs.Unlock(lockBegin, lockEnd);
             fs.Flush();
             //fs.Close();
         }
     }
     catch { }
 }
        static int _m_Lock(RealStatePtr L)
        {
            try {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);


                System.IO.FileStream gen_to_be_invoked = (System.IO.FileStream)translator.FastGetCSObj(L, 1);



                {
                    long _position = LuaAPI.lua_toint64(L, 2);
                    long _length   = LuaAPI.lua_toint64(L, 3);

                    gen_to_be_invoked.Lock(_position, _length);



                    return(0);
                }
            } catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }
        }
Exemplo n.º 6
0
        public override bool Obtain()
        {
            lock (this)
            {
                if (LockExists())
                {
                    // Our instance is already locked:
                    return(false);
                }

                // Ensure that lockDir exists and is a directory.
                bool tmpBool;
                if (System.IO.File.Exists(lockDir.FullName))
                {
                    tmpBool = true;
                }
                else
                {
                    tmpBool = System.IO.Directory.Exists(lockDir.FullName);
                }
                if (!tmpBool)
                {
                    try
                    {
                        System.IO.Directory.CreateDirectory(lockDir.FullName);
                    }
                    catch
                    {
                        throw new System.IO.IOException("Cannot create directory: " + lockDir.FullName);
                    }
                }
                else if (!System.IO.Directory.Exists(lockDir.FullName))
                {
                    throw new System.IO.IOException("Found regular file where directory expected: " + lockDir.FullName);
                }

                System.String canonicalPath = path.FullName;

                bool markedHeld = false;

                try
                {
                    // Make sure nobody else in-process has this lock held
                    // already, and, mark it held if not:

                    lock (LOCK_HELD)
                    {
                        if (LOCK_HELD.Contains(canonicalPath))
                        {
                            // Someone else in this JVM already has the lock:
                            return(false);
                        }
                        else
                        {
                            // This "reserves" the fact that we are the one
                            // thread trying to obtain this lock, so we own
                            // the only instance of a channel against this
                            // file:
                            LOCK_HELD.Add(canonicalPath, canonicalPath);
                            markedHeld = true;
                        }
                    }

                    try
                    {
                        f = new System.IO.FileStream(path.FullName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);
                    }
                    catch (System.IO.IOException 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;
                        f             = null;
                    }

                    if (f != null)
                    {
                        try
                        {
                            channel      = f;
                            lock_Renamed = false;
                            try
                            {
                                channel.Lock(0, channel.Length);
                                lock_Renamed = true;
                            }
                            catch (System.IO.IOException e)
                            {
                                // At least on OS X, we will sometimes get an
                                // intermittent "Permission Denied" IOException,
                                // which seems to simply mean "you failed to get
                                // the lock".  But other IOExceptions could be
                                // "permanent" (eg, locking is not supported via
                                // the filesystem).  So, we record the failure
                                // reason here; the timeout obtain (usually the
                                // one calling us) will use this as "root cause"
                                // if it fails to get the lock.
                                failureReason = e;
                            }
                            finally
                            {
                                if (lock_Renamed == false)
                                {
                                    try
                                    {
                                        channel.Close();
                                    }
                                    finally
                                    {
                                        channel = null;
                                    }
                                }
                            }
                        }
                        finally
                        {
                            if (channel == null)
                            {
                                try
                                {
                                    f.Close();
                                }
                                finally
                                {
                                    f = null;
                                }
                            }
                        }
                    }
                }
                finally
                {
                    if (markedHeld && !LockExists())
                    {
                        lock (LOCK_HELD)
                        {
                            if (LOCK_HELD.Contains(canonicalPath))
                            {
                                LOCK_HELD.Remove(canonicalPath);
                            }
                        }
                    }
                }
                return(LockExists());
            }
        }
Exemplo n.º 7
0
		public override bool Obtain()
		{
			lock (this)
			{
				
				if (LockExists())
				{
					// Our instance is already locked:
					return false;
				}
				
				// Ensure that lockDir exists and is a directory.
				bool tmpBool;
				if (System.IO.File.Exists(lockDir.FullName))
					tmpBool = true;
				else
					tmpBool = System.IO.Directory.Exists(lockDir.FullName);
				if (!tmpBool)
				{
					try
                    {
                        System.IO.Directory.CreateDirectory(lockDir.FullName);
                    }
                    catch
                    {
						throw new System.IO.IOException("Cannot create directory: " + lockDir.FullName);
                    }
				}
				else if (!System.IO.Directory.Exists(lockDir.FullName))
				{
					throw new System.IO.IOException("Found regular file where directory expected: " + lockDir.FullName);
				}
				
				System.String canonicalPath = path.FullName;
				
				bool markedHeld = false;
				
				try
				{
					
					// Make sure nobody else in-process has this lock held
					// already, and, mark it held if not:
					
					lock (LOCK_HELD)
					{
						if (LOCK_HELD.Contains(canonicalPath))
						{
							// Someone else in this JVM already has the lock:
							return false;
						}
						else
						{
							// This "reserves" the fact that we are the one
							// thread trying to obtain this lock, so we own
							// the only instance of a channel against this
							// file:
                            LOCK_HELD.Add(canonicalPath, canonicalPath);
							markedHeld = true;
						}
					}
					
					try
					{
						f = new System.IO.FileStream(path.FullName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite); 
					}
					catch (System.IO.IOException 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;
						f = null;
					}
					
					if (f != null)
					{
						try
						{
							channel = f;
                            lock_Renamed = false;
							try
							{
								channel.Lock(0, channel.Length);
                                lock_Renamed = true;
							}
							catch (System.IO.IOException e)
							{
								// At least on OS X, we will sometimes get an
								// intermittent "Permission Denied" IOException,
								// which seems to simply mean "you failed to get
								// the lock".  But other IOExceptions could be
								// "permanent" (eg, locking is not supported via
								// the filesystem).  So, we record the failure
								// reason here; the timeout obtain (usually the
								// one calling us) will use this as "root cause"
								// if it fails to get the lock.
								failureReason = e;
							}
							finally
							{
								if (lock_Renamed == false)
								{
									try
									{
										channel.Close();
									}
									finally
									{
										channel = null;
									}
								}
							}
						}
						finally
						{
							if (channel == null)
							{
								try
								{
									f.Close();
								}
								finally
								{
									f = null;
								}
							}
						}
					}
				}
				finally
				{
					if (markedHeld && !LockExists())
					{
						lock (LOCK_HELD)
						{
							if (LOCK_HELD.Contains(canonicalPath))
							{
								LOCK_HELD.Remove(canonicalPath);
							}
						}
					}
				}
				return LockExists();
			}
		}
Exemplo n.º 8
0
        /// <summary>  
        /// 写入文本  
        /// </summary>  
        /// <param name="content">文本内容</param>  
        private void Write(string content, string newLine)
        {
            if (string.IsNullOrEmpty(_fileName))
            {
                return;
                //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.UTF8.GetBytes(content + newLine);
                bool flag = true;
                long slen = dataArray.Length;
                long len = 0;
                lock (_lock)
                {
                    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();
            }
        }
        public void ParseRaw(byte[] b, int length)
        {
            if (rawData)
            {
                if (length < 0)
                    throw new System.ArgumentOutOfRangeException("length has to be above zero");

                // Do we have content left that we need to convert?
                if (this.received.Length > 0)
                {
                    byte[] old = this.Encoding.GetBytes(this.received);
            #if !COMPACT_FRAMEWORK
                    long size = (long)length + old.LongLength;

                    byte[] tmp = new byte[size];
                    System.Array.Copy(old, 0, tmp, 0, old.LongLength);
                    if (b != null)
                        System.Array.Copy(b, 0, tmp, old.LongLength, (long)length);
            #else
                    int size = length + old.Length;

                    byte[] tmp = new byte[size];
                    System.Array.Copy(old, 0, tmp, 0, old.Length);
                    if (b != null)
                        System.Array.Copy(b, 0, tmp, old.Length, length);
            #endif
                    b = tmp;
                    length += old.Length;
                    received = string.Empty;
                }

                // Do we have a working byte array?
                if (b != null && length != 0)
                {
                    BinaryMessage conMsg = new BinaryMessage(trans, b, length);
                    // Plugin handling here
                    FmdcEventArgs e = new FmdcEventArgs(Actions.CommandIncomming, conMsg);
                    MessageReceived(trans, e);
                    if (!e.Handled)
                    {
                        if (this.download)
                        {
                            if (trans.DownloadItem != null && trans.CurrentSegment.Index != -1)
                            {
                                if (trans.CurrentSegment.Length < length)
                                {
                                    trans.Disconnect("You are sending more then i want.. Why?!");
                                    return;
                                }

                                if (trans.CurrentSegment.Position == 0 && !Utils.FileOperations.PathExists(trans.DownloadItem.ContentInfo.Get(ContentInfo.STORAGEPATH)))
                                {
                                    Utils.FileOperations.AllocateFile(trans.DownloadItem.ContentInfo.Get(ContentInfo.STORAGEPATH), trans.DownloadItem.ContentInfo.Size);
                                }

                                // Create the file.
                                //using (System.IO.FileStream fs = System.IO.File.OpenWrite(trans.DownloadItem.ContentInfo.Get(ContentInfo.STORAGEPATH)))
                                using (System.IO.FileStream fs = new System.IO.FileStream(trans.DownloadItem.ContentInfo.Get(ContentInfo.STORAGEPATH), System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.Write))
                                {
                                    try
                                    {
                                        // Lock this segment of file
                                        fs.Lock(trans.CurrentSegment.Start, trans.CurrentSegment.Length);
                                        // Set position
                                        fs.Position = trans.CurrentSegment.Start + trans.CurrentSegment.Position;
                                        // Write this byte array to file
                                        fs.Write(b, 0, length);
                                        trans.CurrentSegment.Position += length;
                                        // Saves and unlocks file
                                        fs.Flush();
                                        fs.Unlock(trans.CurrentSegment.Start, trans.CurrentSegment.Length);
                                    }
                                    catch (System.Exception exp)
                                    {
                                        //trans.DownloadItem.Cancel(trans.CurrentSegment.Index, trans.Source);
                                        trans.Disconnect("Exception thrown when trying to write to file: " + exp.ToString());
                                        return;
                                    }
                                    finally
                                    {
                                        fs.Dispose();
                                        fs.Close();
                                    }
                                    if (trans.CurrentSegment.Position >= trans.CurrentSegment.Length)
                                    {
                                        trans.DownloadItem.Finished(trans.CurrentSegment.Index, trans.Source);
                                        //// Searches for a download item and a segment id
                                        // Request new segment from user. IF we have found one. ELSE disconnect.
                                        if (GetSegment(true))
                                        {
                                            OnDownload();
                                        }
                                        else
                                            trans.Disconnect("All content downloaded");
                                    }
                                }
                            }
                        }
                        else
                        {
                            trans.Disconnect("I dont want to download from you. Shove off!");
                        }
                    }
                }
            }
            else
            {
                ParseRaw(this.Encoding.GetString(b, 0, length));
            }
        }