示例#1
0
        /// <summary>
        ///  Gets called after a file action was perforem for example after a rename or copy.
        /// </summary>
        /// <param name="man">ManagerEngine reference that the plugin is assigned to.</param>
        /// <param name="action">File action type.</param>
        /// <param name="file1">File object 1 for example from in a copy operation.</param>
        /// <param name="file2">File object 2 for example to in a copy operation. Might be null in for example a delete.</param>
        /// <returns>true/false if the execution of the event chain should continue execution.</returns>
        public override bool OnFileAction(ManagerEngine man, FileAction action, IFile file1, IFile file2)
        {
            if (action != FileAction.Add)
                return true;

            HttpResponse response = HttpContext.Current.Response;
            HttpRequest request = HttpContext.Current.Request;
            HttpCookie cookie;
            ArrayList chunks;

            if ((cookie = request.Cookies["upl"]) == null)
                cookie = new HttpCookie("upl");

            cookie.Expires = DateTime.Now.AddDays(30);

            if (cookie.Value != null) {
                chunks = new ArrayList(cookie.Value.Split(new char[]{','}));

                if (chunks.IndexOf(man.EncryptPath(file1.AbsolutePath)) == -1)
                    chunks.Add(man.EncryptPath(file1.AbsolutePath));

                cookie.Value = this.Implode(chunks, ",");
            } else
                cookie.Value = man.EncryptPath(file1.AbsolutePath);

            response.Cookies.Remove("upl");
            response.Cookies.Add(cookie);

            return true;
        }
示例#2
0
 public void HandleAction(string input, FileAction action)
 {
     switch (action)
     {
         case FileAction.NewFolder:
             {
                 Directory.CreateDirectory(comboDrive.Text + txtAddress.Text + input);
                 ProcessDirectories(new DirectoryInfo(comboDrive.Text + txtAddress.Text));
                 break;
             }
         case FileAction.NewFile:
             {
                 File.Create(comboDrive.Text + txtAddress.Text + input);
                 ProcessDirectories(new DirectoryInfo(comboDrive.Text + txtAddress.Text));
                 break;
             }
         case FileAction.Delete:
             {
                 if (input.ToLower() == listDir.SelectedItems[0].Text.ToLower())
                 {
                     if (Directory.Exists(comboDrive.Text + txtAddress.Text + listDir.SelectedItems[0].Text))
                         Directory.Delete(comboDrive.Text + txtAddress.Text + listDir.SelectedItems[0].Text);
                     else if (File.Exists(comboDrive.Text + txtAddress.Text + listDir.SelectedItems[0].Text))
                         File.Delete(comboDrive.Text + txtAddress.Text + listDir.SelectedItems[0].Text);
                 }
                 else
                     MessageBox.Show("Error: File/Directory does not exsist.");
                 ProcessDirectories(new DirectoryInfo(comboDrive.Text + txtAddress.Text));
                 break;
             }
     }
 }
示例#3
0
        public void ApplyTo(string startDir, IEnumerable<string> filters, FileAction action)
        {
            var enumerable = filters as IList<string> ?? filters.ToList();
            foreach (var filter in enumerable)
            {
                var files = EnumerateFiles(startDir, filter);
                if (files == null)
                    return;
                foreach (var file in files)
                {
                    action(file);
                }
            } try
            {

                foreach (var directory in Directory.GetDirectories(startDir))
                {
                    ApplyTo(directory, enumerable, action);
                }
            }
            catch (Exception)
            {
                return;
            }
        }
 private void OnFileChange(FileAction action, string fileName, long ticks)
 {
     DateTime minValue;
     if (ticks == 0L)
     {
         minValue = DateTime.MinValue;
     }
     else
     {
         minValue = DateTimeUtil.FromFileTimeToUtc(ticks);
     }
     if (action == FileAction.Dispose)
     {
         if (this._rootCallback.IsAllocated)
         {
             this._rootCallback.Free();
         }
     }
     else if (this._ndirMonCompletionHandle.Handle != IntPtr.Zero)
     {
         using (new ApplicationImpersonationContext())
         {
             this._dirMon.OnFileChange(action, fileName, minValue);
         }
     }
 }
		internal SaveOperationAsyncResult(StorageDevice device, string container, string file, FileAction action, FileMode mode)
		{
			this.storageDevice = device;
			this.containerName = container;
			this.fileName = file;
			this.fileAction = action;
			this.fileMode = mode;
		}
示例#6
0
 private void saveBtn_Click(object sender, RoutedEventArgs e)
 {
     var type = (FileAction.ActionType)Enum.Parse(typeof(FileAction.ActionType), operationCmb.Text);
     var action = new FileAction(type, new FileAction.ActionData() { FileName = fileNameCmb.Text, TargetVar = valueCmb.Text });
     var entity = new StepEntity(action);
     entity.Comment = string.Format("File Action {0}", operationCmb.Text);
     Singleton.Instance<SaveData>().AddStepEntity(entity);
 }
示例#7
0
 public frmInput(frmMain frmObject, string title, string msg, FileAction action)
 {
     InitializeComponent();
     _obj = frmObject;
     this.Text = title;
     lblInfo.Text = msg;
     _action = action;
     this.Show();
     this.Focus();
 }
示例#8
0
 private static bool ExcludedAction(FileAction fileAction)
 {
     switch (fileAction)
     {
         case FileAction.Delete:
         case FileAction.DeleteFrom:
         case FileAction.DeleteInto:
         case FileAction.MoveDelete:
         case FileAction.Purge:
             return true;
         default:
             return false;
     }
 }
		/// <summary>
		/// Saves a file asynchronously.
		/// </summary>
		/// <param name="containerName">The name of the container in which to save the file.</param>
		/// <param name="fileName">The file to save.</param>
		/// <param name="saveAction">The save action to perform.</param>
		/// <param name="userState">A state object used to identify the async operation.</param>
		public void SaveAsync(string containerName, string fileName, FileAction saveAction, object userState)
		{
			// increment our pending operations count
			PendingOperationsIncrement();

			// get a FileOperationState and fill it in
			FileOperationState state = GetFileOperationState();
			state.Container = containerName;
			state.File = fileName;
			state.Action = saveAction;
			state.UserState = userState;

			// queue up the work item
			ThreadPool.QueueUserWorkItem(DoSaveAsync, state);
		}
示例#10
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="man"></param>
        /// <param name="action"></param>
        /// <param name="file1"></param>
        /// <param name="file2"></param>
        /// <returns></returns>
        public override bool OnBeforeFileAction(ManagerEngine man, FileAction action, IFile file1, IFile file2)
        {
            ManagerConfig config;

            if (action == FileAction.Delete) {
                config = file1.Config;

                if (config.GetBool("filesystem.delete_format_images", false)) {
                    ImageUtils.DeleteFormatImages(file1.AbsolutePath, config.Get("upload.format"));
                    ImageUtils.DeleteFormatImages(file1.AbsolutePath, config.Get("edit.format"));
                }
            }

            return true;
        }
示例#11
0
		/// <summary>
		/// Saves a file.
		/// </summary>
		/// <param name="containerName">Used to match the ISaveDevice interface; ignored by the implementation.</param>
		/// <param name="fileName">The file to save.</param>
		/// <param name="saveAction">The save action to perform.</param>
		/// <returns>True if the save completed without errors, false otherwise.</returns>
		public bool Save(string containerName, string fileName, FileAction saveAction)
		{
			if (!Directory.Exists(RootDirectory))
				Directory.CreateDirectory(RootDirectory);

			string path = Path.Combine(RootDirectory, fileName);
			try
			{
				using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write))
					saveAction(stream);
				return true;
			}
			catch 
			{
				return false; 
			}
		}
示例#12
0
		/// <summary>
		/// Loads a file.
		/// </summary>
		/// <param name="containerName">Used to match the ISaveDevice interface; ignored by the implementation.</param>
		/// <param name="fileName">The file to load.</param>
		/// <param name="loadAction">The load action to perform.</param>
		/// <returns>True if the load completed without error, false otherwise.</returns>
		public bool Load(string containerName, string fileName, FileAction loadAction)
		{
			if (!Directory.Exists(RootDirectory))
				Directory.CreateDirectory(RootDirectory);

			string path = Path.Combine(RootDirectory, fileName);
			try
			{
				using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
					loadAction(stream);
				return true;
			}
			catch
			{
				return false;
			}
		}
		/// <summary>
		/// Loads a file.
		/// </summary>
		/// <param name="containerName">The name of the container from which to load the file.</param>
		/// <param name="fileName">The file to load.</param>
		/// <param name="loadAction">The load action to perform.</param>
		public void Load(String containerName, string fileName, FileAction loadAction)
		{
			VerifyIsReady();

			// lock on the storage device so that only one storage operation can occur at a time
			lock (storageDevice)
			{
				// open a container
				using (StorageContainer currentContainer = OpenContainer(containerName))
				{
					// attempt the load
					using (var stream = currentContainer.OpenFile(fileName, FileMode.Open))
					{
						loadAction(stream);
					}
				}
			}
		}
		/// <summary>
		/// Saves a file.
		/// </summary>
		/// <param name="containerName">The name of the container in which to save the file.</param>
		/// <param name="fileName">The file to save.</param>
		/// <param name="saveAction">The save action to perform.</param>
		public void Save(string containerName, string fileName, FileAction saveAction)
		{
			VerifyIsReady();

			// lock on the storage device so that only one storage operation can occur at a time
			lock (storageDevice)
			{
				// open a container
				using (StorageContainer currentContainer = OpenContainer(containerName))
				{
					// attempt the save
					using (var stream = currentContainer.CreateFile(fileName))
					{
						saveAction(stream);
					}
				}
			}
		}
示例#15
0
        /// <summary>
        /// Asks the user to choose a file through an OpenFileDialog
        /// </summary>
        /// <param name="action">The action we want to do with the file</param>
        /// <returns>The file name chosen by the user</returns>
        public string ChooseFile(FileAction action)
        {
            FileDialog fileDialog;

            switch (action)
            {
                case FileAction.Save:
                    fileDialog = new SaveFileDialog();
                    break;

                case FileAction.Open:
                    fileDialog = new OpenFileDialog();
                    break;

                default:
                    throw new ArgumentException("The argument should be a valid FileAction enum value.", "action");
            }

            fileDialog.ShowDialog();

            return fileDialog.FileName;
        }
		/// <summary>
		/// Saves a file.
		/// </summary>
		/// <param name="containerName">The name of the container in which to save the file.</param>
		/// <param name="fileName">The file to save.</param>
		/// <param name="saveAction">The save action to perform.</param>
		public void Save(String containerName, string fileName, FileAction saveAction)
		{
			VerifyIsReady();

#if SILVERLIGHT
            throw new NotSupportedException();
#else

			// lock on the storage device so that only one storage operation can occur at a time
			lock (storageDevice)
			{
				// open a container
				using (StorageContainer currentContainer = OpenContainer(containerName))
				{
                  	// attempt the save
					using (var stream = currentContainer.CreateFile(fileName))
					{
						saveAction(stream);
					}
				}
			}
#endif
        }
示例#17
0
        /// <summary>
        /// 翻译
        /// </summary>
        /// <param name="path">语言包路径</param>
        /// <param name="url">翻译网址</param>
        /// <param name="Lan">翻译类型</param>
        public ActionResult Translate(string path, string url, string Lan)
        {
            string content = FileAction.ReadToStr(path);
            Dictionary <string, string> dic = new Dictionary <string, string>();

            string reg = "msgid \"(?<msgid>.*)\"\r\nmsgstr \"(?<msgstr>.*)\"";

            string[] strArr = DataCheck.GetRegStrArr(content, reg);

            foreach (var str in strArr)
            {
                MatchCollection res = Regex.Matches(str, reg, RegexOptions.IgnoreCase);
                foreach (Match item in res)
                {
                    dic.Add(item.Groups["msgid"].Value, item.Groups["msgstr"].Value);
                }
            }

            SaveLanJs(dic);
            // 发送翻译请求
            // Dictionary<string, string> dicRes= BaiduTranslate(dic, Lan, "");

            return(Content(ResObj.LayerMsg("转换成功!", Icon.Success, "Index")));
        }
示例#18
0
        //private void AddAtWorkStatus(FileAction fileAction)
        //{
        //    while (!_filesInTheWork.TryAdd(fileAction.FilePath, fileAction.ActionType))
        //    {
        //        Task.Delay(1000);
        //    }
        //}

        //private bool IsOperationNeedToContinue(FileAction fileAction)
        //{
        //    if (!_filesInTheWork.ContainsKey(fileAction.FilePath))
        //        return true;

        //    FileActionType actionType;
        //    while (!_filesInTheWork.TryGetValue(FileAction.File));
        //    return true;
        //}

        //private void RemoveAtWorkStatus(FileAction fileAction)
        //{
        //    while (!_filesInTheWork.TryRemove(fileAction.FilePath, out FileActionType type))
        //    {
        //        Task.Delay(1000);
        //    }
        //}

        private void CreateRoutine(FileAction fileAction)
        {
            var filePath = fileAction.FilePath;

            var signatureFilename = OctodiffHelper.GetSignatureName(filePath);
            var signatureFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _tempDirectory, signatureFilename);

            if (File.Exists(signatureFilePath))
            {
                ChangeRoutine(new FileAction(filePath, FileActionType.Changed));
                return;
            }

            OctodiffHelper.BuildSignature(filePath, signatureFilePath);

            byte[] file;
            using (var SourceStream = File.Open(fileAction.FilePath, FileMode.Open))
            {
                file = new byte[SourceStream.Length];
                SourceStream.Read(file, 0, (int)SourceStream.Length);
            }

            _httpSender.SendCreate(file, filePath);
        }
示例#19
0
        private void RecordFileAction(BoxClient client, string fileID, string actionType)
        {
            FileActionService fileActionService = new FileActionService();
            Content           file = GetBoxItem(client, fileID).Result;
            BoxUser           user = client.UsersManager.GetCurrentUserInformationAsync(new String[2] {
                "name", "login"
            }).Result;
            string userName  = user.Name;
            string userEmail = user.Login;

            System.Diagnostics.Debug.WriteLine(userName + " " + userEmail);

            FileAction action = new FileAction(
                fileID,
                file.Hash,
                "Box",
                userName,
                userEmail,
                actionType,
                DateTime.Now
                );

            fileActionService.RecordFileAction(action);
        }
示例#20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="man"></param>
        /// <param name="action"></param>
        /// <param name="file1"></param>
        /// <param name="file2"></param>
        /// <returns></returns>
        public override bool OnFileAction(ManagerEngine man, FileAction action, IFile file1, IFile file2)
        {
            IFile         thumbnailFolder, thumbnail;
            ManagerConfig config;

            switch (action)
            {
            case FileAction.Add:
                config = file1.Config;

                if (config.Get("upload.format") != null)
                {
                    ImageUtils.FormatImage(file1.AbsolutePath, config.Get("upload.format"), config.GetInt("upload.autoresize_jpeg_quality", 90));
                }

                if (config.GetBool("upload.create_thumbnail", true))
                {
                    thumbnail = this.MakeThumb(man, file1);
                }

                if (config.GetBool("upload.autoresize", false))
                {
                    string ext = PathUtils.GetExtension(file1.Name).ToLower();
                    int    newWidth, newHeight, configWidth, configHeight;
                    double scale;

                    // Validate format
                    if (ext != "gif" && ext != "jpeg" && ext != "jpg" && ext != "png")
                    {
                        return(true);
                    }

                    MediaInfo imageInfo = new MediaInfo(file1.AbsolutePath);

                    configWidth  = config.GetInt("upload.max_width", 1024);
                    configHeight = config.GetInt("upload.max_height", 768);

                    // Needs scaling?
                    if (imageInfo.Width > configWidth || imageInfo.Height > configHeight)
                    {
                        scale     = Math.Min(configWidth / (double)imageInfo.Width, configHeight / (double)imageInfo.Height);
                        newWidth  = scale > 1 ? imageInfo.Width : (int)Math.Floor(imageInfo.Width * scale);
                        newHeight = scale > 1 ? imageInfo.Height : (int)Math.Floor(imageInfo.Height * scale);

                        ImageUtils.ResizeImage(file1.AbsolutePath, file1.AbsolutePath, newWidth, newHeight, config.GetInt("upload.autoresize_jpeg_quality", 90));
                    }
                }

                break;

            case FileAction.Delete:
                config = file1.Config;

                if (config.GetBool("thumbnail.delete", true))
                {
                    thumbnailFolder = man.GetFile(file1.Parent, config["thumbnail.folder"]);
                    thumbnail       = man.GetFile(thumbnailFolder.AbsolutePath, config.Get("thumbnail.prefix", "mcith") + file1.Name);

                    if (thumbnail.Exists)
                    {
                        thumbnail.Delete();
                    }

                    // Delete empty thumbnail folder
                    if (thumbnailFolder.Exists && thumbnailFolder.ListFiles().Length == 0)
                    {
                        thumbnailFolder.Delete();
                    }
                }
                break;
            }

            return(true);
        }
示例#21
0
 public FileSubmitRecord(FileAction action, FileSpec file)
 {
     _action = action;
     File    = file;
 }
示例#22
0
        /// <summary>
        /// Asynchronously uploads a local file specified in the path parameter to the remote FTP server.   
        /// </summary>
        /// <param name="localPath">Path to a file on the local machine.</param>
        /// <param name="action">The type of put action taken.</param>
        /// <remarks>
        /// The file is uploaded to the current working directory on the remote server. 
        /// </remarks>
        /// <seealso cref="PutFileAsyncCompleted"/>
        /// <seealso cref="FtpBase.CancelAsync"/>
        /// <seealso cref="PutFile(string, string, FileAction)"/>
        /// <seealso cref="PutFileUnique(string)"/>
        /// <seealso cref="GetFile(string, string, FileAction)"/>
        /// <seealso cref="GetFileAsync(string, string, FileAction)"/>
        /// <seealso cref="MoveFile"/>
        /// <seealso cref="FxpCopy"/>
        /// <seealso cref="FxpCopyAsync"/>    
        public void PutFileAsync(string localPath, FileAction action)
        {
            if (base.AsyncWorker != null && base.AsyncWorker.IsBusy)
                throw new InvalidOperationException("The FtpClient object is already busy executing another asynchronous operation.  You can only execute one asychronous method at a time.");

            base.CreateAsyncWorker();
            base.AsyncWorker.WorkerSupportsCancellation = true;
            base.AsyncWorker.DoWork += new DoWorkEventHandler(PutFileLocalAsync_DoWork);
            base.AsyncWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(PutFileAsync_RunWorkerCompleted);
            Object[] args = new Object[2];
            args[0] = localPath;
            args[1] = action;
            base.AsyncWorker.RunWorkerAsync(args);
        }
示例#23
0
 /// <summary>
 /// Uploads a local file specified in the path parameter to the remote FTP server.   
 /// </summary>
 /// <param name="localPath">Path to a file on the local machine.</param>
 /// <param name="action">The type of put action taken.</param>
 /// <remarks>
 /// The file is uploaded to the current working directory on the remote server. 
 /// </remarks>
 /// <seealso cref="PutFileAsync(string, string, FileAction)"/>
 /// <seealso cref="PutFileUnique(string)"/>
 /// <seealso cref="GetFile(string, string, FileAction)"/>
 /// <seealso cref="GetFileAsync(string, string, FileAction)"/>
 /// <seealso cref="MoveFile"/>
 /// <seealso cref="FxpCopy"/>
 /// <seealso cref="FxpCopyAsync"/>            
 public void PutFile(string localPath, FileAction action)
 {
     using (FileStream fileStream = File.OpenRead(localPath))
     {
         PutFile(fileStream, ExtractPathItemName(localPath), action);
     }
 }
示例#24
0
        /// <summary>
        /// Retrieves a remote file from the FTP server and writes the data to a local file
        /// specfied in the localPath parameter.
        /// </summary>
        /// <remarks>
        /// Note that some FTP servers will not accept a full path.  On those systems you must navigate to
        /// the directory you wish to get the file using with the ChangeDirectory() or ChangeDirectoryMultiPath()
        /// method.
        /// </remarks>
        /// <param name="remotePath">A path and/or file name to the remote file.</param>
        /// <param name="localPath">A fully qualified local path to a file on the local machine.</param>
        /// <param name="action">The type of action to take.</param>
        /// <seealso cref="GetFileAsync(string, string, FileAction)"/>
        /// <seealso cref="PutFile(string, string, FileAction)"/>
        /// <seealso cref="PutFileAsync(string, string, FileAction)"/>
        /// <seealso cref="MoveFile"/>
        /// <seealso cref="FxpCopy"/>
        /// <seealso cref="FxpCopyAsync"/>
        public void GetFile(string remotePath, string localPath, FileAction action)
        {
            if (remotePath == null)
                throw new ArgumentNullException("remotePath");

            if (remotePath.Length == 0)
                throw new ArgumentException("must contain a value", "remotePath");

            if (localPath == null)
                throw new ArgumentNullException("localPath");

            if (localPath.Length == 0)
                throw new ArgumentException("must contain a value", "localPath");

            if (action == FileAction.None)
                throw new ArgumentOutOfRangeException("action", "must contain a value other than 'Unknown'");

            localPath = CorrectLocalPath(localPath);

            WriteToLog(String.Format("Action='GetFile';Status='TransferBegin';LocalPath='{0}';RemotePath='{1}';FileAction='{1}'", localPath, remotePath, action.ToString()));

            FtpRequest request = new FtpRequest(base.CharacterEncoding, FtpCmd.Retr, remotePath);

            try
            {
                switch (action)
                {
                    case FileAction.CreateNew:
                        // create a file stream to stream the file locally to disk that only creates the file if it does not already exist
                        using (Stream localFile = File.Open(localPath, FileMode.CreateNew))
                        {
                            base.TransferData(TransferDirection.ToClient, request, localFile);
                        }
                        break;

                    case FileAction.Create:
                        // create a file stream to stream the file locally to disk
                        using (Stream localFile = File.Open(localPath, FileMode.Create))
                        {
                            base.TransferData(TransferDirection.ToClient, request, localFile);
                        }
                        break;
                    case FileAction.CreateOrAppend:
                        // open the local file
                        using (Stream localFile = File.Open(localPath, FileMode.OpenOrCreate))
                        {
                            // set the file position to the end so that any new data will be appended
                            localFile.Position = localFile.Length;
                            base.TransferData(TransferDirection.ToClient, request, localFile);
                        }
                        break;
                    case FileAction.Resume:
                        using (Stream localFile = File.Open(localPath, FileMode.Open))
                        {
                            //  get the size of the file already on the server (in bytes)
                            long remoteSize = GetFileSize(remotePath);

                            // if the files are the same size then there is nothing to transfer
                            if (localFile.Length == remoteSize)
                                return;

                            base.TransferData(TransferDirection.ToClient, request, localFile, localFile.Length - 1);
                        }
                        break;
                    case FileAction.ResumeOrCreate:
                        if (File.Exists(localPath) && (new FileInfo(localPath)).Length > 0)
                            GetFile(remotePath, localPath, FileAction.Resume);
                        else
                            GetFile(remotePath, localPath, FileAction.Create);
                        break;
                }
            }
            catch (Exception ex)
            {
                WriteToLog(String.Format("Action='GetFile';Status='TransferError';LocalPath='{0}';RemotePath='{1}';FileAction='{1}';ErrorMessage='{2}", localPath, remotePath, action.ToString(), ex.Message));
                throw new FtpException(String.Format("An unexpected exception occurred while retrieving file '{0}'.", remotePath), base.LastResponse, ex);
            }

            WriteToLog(String.Format("Action='GetFile';Status='TransferSuccess';LocalPath='{0}';RemotePath='{1}';FileAction='{1}'", localPath, remotePath, action.ToString()));
        }
示例#25
0
        void ProcessEvent(kevent ev)
        {
            lock (this)
            {
                KeventData data = (KeventData)requests [ev.ident];
                if (!data.Enabled)
                {
                    return;
                }

                FileSystemWatcher fsw;
                string            filename = "";

                fsw = data.FSW;
                FileAction     fa         = 0;
                DirectoryInfo  dir        = new DirectoryInfo(data.Directory);
                FileSystemInfo changedFsi = null;

                try
                {
                    foreach (FileSystemInfo fsi in dir.GetFileSystemInfos())
                    {
                        if (data.DirEntries.ContainsKey(fsi.FullName) && (fsi is FileInfo))
                        {
                            KeventFileData entry = (KeventFileData)data.DirEntries [fsi.FullName];
                            if (entry.LastWriteTime != fsi.LastWriteTime)
                            {
                                filename = fsi.Name;
                                fa       = FileAction.Modified;
                                data.DirEntries [fsi.FullName] = new KeventFileData(fsi, fsi.LastAccessTime, fsi.LastWriteTime);
                                if (fsw.IncludeSubdirectories && fsi is DirectoryInfo)
                                {
                                    data.Directory      = filename;
                                    requests [ev.ident] = data;
                                    ProcessEvent(ev);
                                }
                                PostEvent(filename, fsw, fa, changedFsi);
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    // The file system infos were changed while we processed them
                }
                // Deleted
                try
                {
                    bool deleteMatched = true;
                    while (deleteMatched)
                    {
                        foreach (KeventFileData entry in data.DirEntries.Values)
                        {
                            if (!File.Exists(entry.fsi.FullName) && !Directory.Exists(entry.fsi.FullName))
                            {
                                filename = entry.fsi.Name;
                                fa       = FileAction.Removed;
                                data.DirEntries.Remove(entry.fsi.FullName);
                                PostEvent(filename, fsw, fa, changedFsi);
                                break;
                            }
                        }
                        deleteMatched = false;
                    }
                }
                catch (Exception)
                {
                    // The file system infos were changed while we processed them
                }
                // Added
                try
                {
                    foreach (FileSystemInfo fsi in dir.GetFileSystemInfos())
                    {
                        if (!data.DirEntries.ContainsKey(fsi.FullName))
                        {
                            changedFsi = fsi;
                            filename   = fsi.Name;
                            fa         = FileAction.Added;
                            data.DirEntries [fsi.FullName] = new KeventFileData(fsi, fsi.LastAccessTime, fsi.LastWriteTime);
                            PostEvent(filename, fsw, fa, changedFsi);
                        }
                    }
                }
                catch (Exception)
                {
                    // The file system infos were changed while we processed them
                }
            }
        }
示例#26
0
        private void bt_Start_Click(object sender, EventArgs e)
        {
            //CheckBox temp;
            //Crawler crawler = new Crawler();

            //crawler.OnCompleted += Crawler_OnCompleted;
            //crawler.OnError += Crawler_OnError;


            //foreach (Control item in pl_UrlList.Controls) {
            //    if (item is CheckBox) {
            //        temp = item as CheckBox;
            //        if (temp.Checked) {

            //            SetLog("开始爬取:" + temp.Text, Color.Black);
            //            crawler.Start(temp.Tag + "", "<a[^>]+?href=[\"']?http://3g.163.com/all/article/([^\"']+)[\"']?[^>]*>(.+?)</a>").Wait();
            //        }
            //        temp.Enabled = true;
            //    }

            //}
            //SetLog("结束!", Color.OrangeRed);

            #region 翻译

            string ReadPath = @"F:\01.Porject\NanNing\050Coding\New_NaNing_SSC\WebFront\App_Data\Localization\en\orchard.module.po";
            string SavePath = @"F:\orchard.module.po";

            string content = FileAction.ReadToStr(ReadPath);


            string reg = "msgid \"(?<msgid>.*)\" \r\nmsgstr \"(?<msgstr>.*)\"";

            string[]  strArr    = DataCheck.GetRegStrArr(content, reg);
            Translate translate = new Translate("20171116000095832", "PuVyBlMqMOOjqfks4GJ7");

            // 记录运行时间
            Stopwatch watch = new Stopwatch();

            int con = 0;

            foreach (var str in strArr)
            {
                SetLog("开始翻译!", Color.Black);

                watch.Start();

                MatchCollection res = Regex.Matches(str, reg, RegexOptions.IgnoreCase);
                foreach (Match item in res)
                {
                    //  BaiduTransAPI transAPI = translate.BaiduTranslate(item.Groups["msgid"].Value, "zh", "en");

                    string context = "" +
                                     "msgid \"" + item.Groups["msgid"].Value + "\"\n" +
                                     "msgstr \"" + Utils.StrToUpper(item.Groups["msgstr"].Value, 2) + "\"\n\n";

                    FileAction.AppendStr(SavePath, context);
                }
                SetLog("翻译结束,用时:" + watch.ElapsedMilliseconds * 0.1 / 1000 + " s,第" + (++con) + "条", Color.Brown);
                watch.Stop();
            }

            #endregion

            bt_Start.Enabled = true;
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="containerName"></param>
 /// <param name="fileName"></param>
 /// <param name="loadAction"></param>
 public void Load(String containerName, String fileName, FileAction loadAction)
 {
     loadAction.Invoke(TitleContainer.OpenStream(String.Join(@"\", containerName, fileName)));
 }
示例#28
0
        public ValidationError IsValid()
        {
            if (string.IsNullOrEmpty(Name))
            {
                return(new ValidationError("Shortcut Name Cannot be Empty.", this));
            }

            foreach (Action action in Actions)
            {
                switch (action.Type)
                {
                case "command":
                    CommandAction   a1    = action as CommandAction;
                    ValidationError a1Err = a1.IsValid();
                    if (a1Err != null)
                    {
                        a1Err.Shortcut = this;
                        return(a1Err);
                    }

                    break;

                case "file":
                    FileAction      a2    = action as FileAction;
                    ValidationError a2Err = a2.IsValid();
                    if (a2Err != null)
                    {
                        a2Err.Shortcut = this;
                        return(a2Err);
                    }

                    break;

                case "folder":
                    FolderAction    a3    = action as FolderAction;
                    ValidationError a3Err = a3.IsValid();
                    if (a3Err != null)
                    {
                        a3Err.Shortcut = this;
                        return(a3Err);
                    }

                    break;

                case "software":
                    SoftwareAction  a4    = action as SoftwareAction;
                    ValidationError a4Err = a4.IsValid();
                    if (a4Err != null)
                    {
                        a4Err.Shortcut = this;
                        return(a4Err);
                    }

                    break;

                case "website":
                    WebsiteAction   a5    = action as WebsiteAction;
                    ValidationError a5Err = a5.IsValid();
                    if (a5Err != null)
                    {
                        a5Err.Shortcut = this;
                        return(a5Err);
                    }

                    break;
                }
            }

            return(null);
        }
示例#29
0
	//
	// Renders the id/serial representation for review by the administrator.
	//
	void RenderReview (int id, int serial)
	{
		current_id = id;
		current_serial = serial;
		
		notebook.Page = 1;

		GlobalChangeset globalset;
		globalset = LoadReview (id, serial);

		HTMLStream s = html_review.Begin ("text/html");
		s.Write ("<html><body>");
		if (globalset == null){
			s.Write ("No data found");
			html_review.End (s, HTMLStreamStatus.Ok);
			return;
		}

		int key = 0;
		action_map = new Hashtable ();
		
		//
		// First make sure we dont have sources that we dont know about,
		// so a contribution can not be flagged as done by accident
		//
		bool allow_flag_as_done = true;
		foreach (DocSetChangeset docset in globalset.DocSetChangesets){
			if (!providers.Contains (docset.DocSet)){
				s.Write (String.Format ("<font color='red'>Warning: Skipping {0}</font>", docset.DocSet));
				allow_flag_as_done = false;
				continue;
			}
		}

		if (allow_flag_as_done)
			s.Write (String.Format ("<h1>Changes: <a href=\"flag-done:{0}${1}\">[Flag as Done]</a></h1>", id, serial));

		foreach (DocSetChangeset docset in globalset.DocSetChangesets){
			if (!providers.Contains (docset.DocSet))
				continue;
			
			if (docset == null){
				s.Write ("Null?");
				continue;
			}
			string ds;

			ds = String.Format ("<table width='100%' bgcolor='#aabbaa'><tr><td>Docset: {0}</td></tr></table>", docset.DocSet);
			foreach (FileChangeset fileset in docset.FileChangesets){
				string fs, es = null;

				fs = String.Format ("<h3><a href=\"apply-file:{0}\">[Apply]</a> File: {1} <br><blockquote>",
						    key, fileset.RealFile);
				
				action_map [key++] = new FileAction (globalset, docset, fileset);

				if (fileset.RealFile == null){
					s.Write (String.Format ("Warning: invalid contribution, its missing filename"));
					continue;
				}
				XmlDocument d = LoadDocument (docset, fileset.RealFile);
				
				foreach (Change c in fileset.Changes){
					XmlNode orig = d.SelectSingleNode (c.XPath);
					XmlNode newn = c.NewNode;

					if (orig == null){
						s.Write (String.Format ("Warning, node {0} does not exist", c.XPath));
						continue;
					}

					if (ds != null) { s.Write (ds); ds = null; }
					if (fs != null) { s.Write (fs); fs = null; es = "</blockquote>"; }

					string original_text = orig.InnerXml;
					string new_text = c.NewNode.InnerXml;

					if (original_text == new_text){
						//s.Write ("<b>Applied</b><br>");
						continue;
					}
					
					int p = c.XPath.LastIndexOf ("/");
					s.Write (String.Format ("<a href=\"diff-change:{0}\">[Diff]</a>", key));
					s.Write (String.Format ("<a href=\"apply-change:{0}\">[Apply]</a>: {1} ", key, c.XPath));
					if (c.FromVersion != RootTree.MonodocVersion)
						s.Write ("<b>FROM OLD VERSION</b>");
					action_map [key++] = new ItemAction (globalset, docset, fileset, c);
					s.Write ("<table border=1 width=100%><tr bgcolor=grey><td width=50%>Current</td><td width=50%>New</td>");

					s.Write ("<tr>");
					s.Write (String.Format ("<td>{0}</td>", Htmlize (original_text)));
					
					s.Write ("<td>");
					s.Write (Htmlize (new_text));
					s.Write ("</td></tr>");
					s.Write ("</table>");
				}
				if (es != null) s.Write (es);
			}
		}
		s.Write ("</body></html>");
		html_review.End (s, HTMLStreamStatus.Ok);
	}
示例#30
0
 /// <summary>
 ///  Gets called after a file action was perforem for example after a rename or copy.
 /// </summary>
 /// <param name="man">ManagerEngine reference that the plugin is assigned to.</param>
 /// <param name="action">File action type.</param>
 /// <param name="file1">File object 1 for example from in a copy operation.</param>
 /// <param name="file2">File object 2 for example to in a copy operation. Might be null in for example a delete.</param>
 /// <returns>true/false if the execution of the event chain should continue execution.</returns>
 public virtual bool OnFileAction(ManagerEngine man, FileAction action, IFile file1, IFile file2)
 {
     return(true);
 }
示例#31
0
        /// <summary>
        /// 写入日志文本
        /// </summary>
        /// <param name="context">内容</param>
        public void SetLogTxt(string context)
        {
            string path = Path.GetFullPath($"../../LogTxt/{DateTime.Now.ToString("yyyy-MM-dd")}.txt");

            FileAction.AppendStr(path, context);
        }
 public void OnNext(FileAction fileAction)
 {
     _processor.Process(fileAction);
 }
示例#33
0
 public void tryDeselectFile()
 {
     _queuedAction = FileAction.Deselect;
 }
示例#34
0
文件: KeventWatcher.cs 项目: av8/mono
		private void PostEvent (string filename, FileSystemWatcher fsw, FileAction fa, FileSystemInfo changedFsi) {
			RenamedEventArgs renamed = null;
			if (fa == 0)
				return;
			
			if (fsw.IncludeSubdirectories && fa == FileAction.Added) {
				if (changedFsi is DirectoryInfo) {
					KeventData newdirdata = new KeventData ();
					newdirdata.FSW = fsw;
					newdirdata.Directory = changedFsi.FullName;
					newdirdata.FileMask = fsw.MangledFilter;
					newdirdata.IncludeSubdirs = fsw.IncludeSubdirectories;
	
					newdirdata.Enabled = true;
					lock (this) {
						StartMonitoringDirectory (newdirdata);
					}
				}
			}
		
			if (!fsw.Pattern.IsMatch(filename, true))
				return;

			lock (fsw) {
				if (changedFsi.FullName.StartsWith (fsw.FullPath, StringComparison.Ordinal))
					filename = changedFsi.FullName.Substring (fsw.FullPath.Length + 1);
				fsw.DispatchEvents (fa, filename, ref renamed);
				if (fsw.Waiting) {
					fsw.Waiting = false;
					System.Threading.Monitor.PulseAll (fsw);
				}
			}
		}
示例#35
0
        private void SetSelection(FileAction fa)
        {
            var selection = ItemsView.SelectedItems.Select(s => s.Path);

            FilesystemAction.SetClipboard <FileItem>(fa, selection);
        }
示例#36
0
        /// <inheritdoc />
        public override BlockBase FromLS(string line)
        {
            // Trim the line
            var input = line.Trim();

            // Parse the label
            if (input.StartsWith("#"))
            {
                Label = LineParser.ParseLabel(ref input);
            }

            // Parse the function
            Group = (UtilityGroup)LineParser.ParseEnum(ref input, "Group", typeof(UtilityGroup));

            // Parse specific function parameters
            switch (Group)
            {
            case UtilityGroup.List:

                ListName   = LineParser.ParseLiteral(ref input, "List Name");
                ListAction = (ListAction)LineParser.ParseEnum(ref input, "List Action", typeof(ListAction));

                switch (ListAction)
                {
                case ListAction.Join:
                    Separator = LineParser.ParseLiteral(ref input, "Separator");
                    break;

                case ListAction.Concat:
                case ListAction.Zip:
                case ListAction.Map:
                    SecondListName = LineParser.ParseLiteral(ref input, "Second List Name");
                    break;

                case ListAction.Add:
                    ListItem  = LineParser.ParseLiteral(ref input, "Item");
                    ListIndex = LineParser.ParseLiteral(ref input, "Index");
                    break;

                case ListAction.Remove:
                    ListIndex = LineParser.ParseLiteral(ref input, "Index");
                    break;
                }
                break;

            case UtilityGroup.Variable:
                VarName   = LineParser.ParseLiteral(ref input, "Var Name");
                VarAction = (VarAction)LineParser.ParseEnum(ref input, "Var Action", typeof(VarAction));

                switch (VarAction)
                {
                case VarAction.Split:
                    SplitSeparator = LineParser.ParseLiteral(ref input, "Separator");
                    break;
                }
                break;

            case UtilityGroup.Conversion:
                ConversionFrom = (Conversion)LineParser.ParseEnum(ref input, "Conversion From", typeof(Conversion));
                ConversionTo   = (Conversion)LineParser.ParseEnum(ref input, "Conversion To", typeof(Conversion));
                InputString    = LineParser.ParseLiteral(ref input, "Input");
                break;

            case UtilityGroup.File:
                FilePath   = LineParser.ParseLiteral(ref input, "File Name");
                FileAction = (FileAction)LineParser.ParseEnum(ref input, "File Action", typeof(FileAction));

                switch (FileAction)
                {
                case FileAction.Write:
                case FileAction.WriteLines:
                case FileAction.Append:
                case FileAction.AppendLines:
                    InputString = LineParser.ParseLiteral(ref input, "Input String");
                    break;
                }
                break;
            }

            // Try to parse the arrow, otherwise just return the block as is with default var name and var / cap choice
            if (LineParser.ParseToken(ref input, TokenType.Arrow, false) == "")
            {
                return(this);
            }

            // Parse the VAR / CAP
            try
            {
                var varType = LineParser.ParseToken(ref input, TokenType.Parameter, true);
                if (varType.ToUpper() == "VAR" || varType.ToUpper() == "CAP")
                {
                    IsCapture = varType.ToUpper() == "CAP";
                }
            }
            catch { throw new ArgumentException("Invalid or missing variable type"); }

            // Parse the variable/capture name
            try { VariableName = LineParser.ParseToken(ref input, TokenType.Literal, true); }
            catch { throw new ArgumentException("Variable name not specified"); }

            return(this);
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="containerName"></param>
 /// <param name="fileName"></param>
 /// <param name="saveAction"></param>
 public void Save(String containerName, string fileName, FileAction saveAction)
 {
     throw new NotSupportedException("Can not save to the title container.");
 }
示例#38
0
        private void ProcessEvents()
        {
            ArrayList arrayList = null;

            lock (this)
            {
                string text;
                int    num;
                int    num2;
                while (FAMWatcher.InternalFAMNextEvent(ref FAMWatcher.conn, out text, out num, out num2) == 1)
                {
                    bool flag;
                    switch (num)
                    {
                    case 1:
                    case 2:
                    case 5:
                        flag = FAMWatcher.requests.ContainsKey(num2);
                        break;

                    case 3:
                    case 4:
                    case 6:
                    case 7:
                    case 8:
                    case 9:
                        goto IL_75;

                    default:
                        goto IL_75;
                    }
IL_7D:
                    if (flag)
                    {
                        FAMData famdata = (FAMData)FAMWatcher.requests[num2];
                        if (famdata.Enabled)
                        {
                            FileSystemWatcher fsw              = famdata.FSW;
                            NotifyFilters     notifyFilter     = fsw.NotifyFilter;
                            RenamedEventArgs  renamedEventArgs = null;
                            FileAction        fileAction       = (FileAction)0;
                            if (num == 1 && (notifyFilter & (NotifyFilters.Attributes | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Size)) != (NotifyFilters)0)
                            {
                                fileAction = FileAction.Modified;
                            }
                            else if (num == 2)
                            {
                                fileAction = FileAction.Removed;
                            }
                            else if (num == 5)
                            {
                                fileAction = FileAction.Added;
                            }
                            if (fileAction != (FileAction)0)
                            {
                                if (fsw.IncludeSubdirectories)
                                {
                                    string fullPath = fsw.FullPath;
                                    string text2    = famdata.Directory;
                                    if (text2 != fullPath)
                                    {
                                        int length = fullPath.Length;
                                        int num3   = 1;
                                        if (length > 1 && fullPath[length - 1] == Path.DirectorySeparatorChar)
                                        {
                                            num3 = 0;
                                        }
                                        string path = text2.Substring(fullPath.Length + num3);
                                        text2 = Path.Combine(text2, text);
                                        text  = Path.Combine(path, text);
                                    }
                                    else
                                    {
                                        text2 = Path.Combine(fullPath, text);
                                    }
                                    if (fileAction == FileAction.Added && Directory.Exists(text2))
                                    {
                                        if (arrayList == null)
                                        {
                                            arrayList = new ArrayList(4);
                                        }
                                        arrayList.Add(new FAMData
                                        {
                                            FSW            = fsw,
                                            Directory      = text2,
                                            FileMask       = fsw.MangledFilter,
                                            IncludeSubdirs = true,
                                            SubDirs        = new Hashtable(),
                                            Enabled        = true
                                        });
                                        arrayList.Add(famdata);
                                    }
                                }
                                if (!(text != famdata.Directory) || fsw.Pattern.IsMatch(text))
                                {
                                    FileSystemWatcher obj = fsw;
                                    lock (obj)
                                    {
                                        fsw.DispatchEvents(fileAction, text, ref renamedEventArgs);
                                        if (fsw.Waiting)
                                        {
                                            fsw.Waiting = false;
                                            System.Threading.Monitor.PulseAll(fsw);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (FAMWatcher.FAMPending(ref FAMWatcher.conn) <= 0)
                    {
                        goto IL_28F;
                    }
                    continue;
IL_75:
                    flag = false;
                    goto IL_7D;
                }
                return;
            }
IL_28F:
            if (arrayList != null)
            {
                int count = arrayList.Count;
                for (int i = 0; i < count; i += 2)
                {
                    FAMData famdata2 = (FAMData)arrayList[i];
                    FAMData famdata3 = (FAMData)arrayList[i + 1];
                    FAMWatcher.StartMonitoringDirectory(famdata2, true);
                    FAMWatcher.requests[famdata2.Request.ReqNum] = famdata2;
                    FAMData obj2 = famdata3;
                    lock (obj2)
                    {
                        famdata3.SubDirs[famdata2.Directory] = famdata2;
                    }
                }
                arrayList.Clear();
            }
        }
示例#39
0
        public void ResolveRecordsTest()
        {
            DepotPath                movedfile            = new DepotPath("//depot/main/movedfile");
            bool                     ismapped             = true;
            bool                     shelved              = true;
            FileAction               headaction           = new FileAction();
            int                      headchange           = 0;
            int                      headrev              = 0;
            FileType                 headtype             = null;
            DateTime                 headtime             = new DateTime();
            DateTime                 headmodtime          = new DateTime();
            int                      movedrev             = 0;
            int                      haverev              = 0;
            string                   desc                 = "";
            string                   digest               = "";
            int                      filesize             = 0;
            FileAction               action               = FileAction.Abandoned;
            FileType                 type                 = null;
            string                   actionowner          = "";
            int                      change               = 0;
            bool                     resolved             = true;
            bool                     unresolved           = true;
            bool                     reresolvable         = true;
            int                      otheropen            = -1;
            List <string>            otheropenuserclients = null;
            bool                     otherlock            = true;
            List <string>            otherlockuserclients = null;
            List <FileAction>        otheractions         = null;
            List <int>               otherchanges         = null;
            bool                     ourlock              = true;
            List <FileResolveAction> resolverecords       = new List <FileResolveAction>();

            FileResolveAction Rec1 = new FileResolveAction
                                         (ResolveAction.Ignored, new FileSpec(new DepotPath("main/file1"), new Revision(1)),
                                         new FileSpec(new DepotPath("dev/file1"), new Revision(1)), 24, 48);

            FileResolveAction Rec2 = new FileResolveAction
                                         (ResolveAction.CopyFrom, new FileSpec(new DepotPath("rel1/file3"), new Revision(3)),
                                         new FileSpec(new DepotPath("main/file3"), new Revision(2)), 24, 48);

            Dictionary <String, Object> attributes       = null;
            Dictionary <String, Object> attributedigests = null;

            FileMetaData target = new FileMetaData
                                      (movedfile, ismapped, shelved,
                                      headaction, headchange, headrev, headtype,
                                      headtime, headmodtime, movedrev, haverev,
                                      desc, digest, filesize, action, type,
                                      actionowner, change, resolved, unresolved,
                                      reresolvable, otheropen, otheropenuserclients,
                                      otherlock, otherlockuserclients, otheractions,
                                      otherchanges, ourlock, resolverecords, attributes,
                                      attributedigests, null, null, null, -1, null
                                      );
            List <FileResolveAction> expected = resolverecords;

            target.ResolveRecords.Add(Rec1);
            target.ResolveRecords.Add(Rec2);
            Assert.AreEqual(Rec1, target.ResolveRecords[0]);
            Assert.AreEqual(Rec2, target.ResolveRecords[1]);
            IList <FileResolveAction> actual;

            target.ResolveRecords = expected;
            actual = target.ResolveRecords;
            Assert.AreEqual(expected, actual);
        }
示例#40
0
        public void GetFile(string remotePath, string localPath, FileAction action)
        {
            if (remotePath == null)
            {
                throw new ArgumentNullException("remotePath");
            }

            if (remotePath.Length == 0)
            {
                throw new ArgumentException("must contain a value", "remotePath");
            }

            if (localPath == null)
            {
                throw new ArgumentNullException("localPath");
            }

            if (localPath.Length == 0)
            {
                throw new ArgumentException("must contain a value", "localPath");
            }

            if (action == FileAction.None)
            {
                throw new ArgumentOutOfRangeException("action", "must contain a value other than 'Unknown'");
            }

            localPath = CorrectLocalPath(localPath);
            WriteToLog(String.Format("Action='GetFile';Status='TransferBegin';LocalPath='{0}';RemotePath='{1}';FileAction='{1}'", localPath, remotePath, action));
            FtpRequest request = new FtpRequest(base.CharacterEncoding, FtpCmd.Retr, remotePath);

            try
            {
                switch (action)
                {
                    case FileAction.CreateNew:
                        using (Stream localFile = File.Open(localPath, FileMode.CreateNew))
                        {
                            base.TransferData(TransferDirection.ToClient, request, localFile);
                        }

                        break;
                    case FileAction.Create:
                        using (Stream localFile = File.Open(localPath, FileMode.Create))
                        {
                            base.TransferData(TransferDirection.ToClient, request, localFile);
                        }

                        break;
                    case FileAction.CreateOrAppend:
                        using (Stream localFile = File.Open(localPath, FileMode.OpenOrCreate))
                        {
                            localFile.Position = localFile.Length;
                            base.TransferData(TransferDirection.ToClient, request, localFile);
                        }

                        break;
                    case FileAction.Resume:
                        using (Stream localFile = File.Open(localPath, FileMode.Open))
                        {
                            long remoteSize = GetFileSize(remotePath);

                            if (localFile.Length == remoteSize)
                            {
                                return;
                            }

                            base.TransferData(TransferDirection.ToClient, request, localFile, localFile.Length - 1);
                        }

                        break;
                    case FileAction.ResumeOrCreate:
                        if (File.Exists(localPath) && (new FileInfo(localPath)).Length > 0)
                        {
                            GetFile(remotePath, localPath, FileAction.Resume);
                        }
                        else
                        {
                            GetFile(remotePath, localPath, FileAction.Create);
                        }

                        break;
                }
            }
            catch (Exception ex)
            {
                WriteToLog(String.Format("Action='GetFile';Status='TransferError';LocalPath='{0}';RemotePath='{1}';FileAction='{1}';ErrorMessage='{2}", localPath, remotePath, action, ex.Message));
                throw new FtpException(String.Format("An unexpected exception occurred while retrieving file '{0}'.", remotePath), base.LastResponse, ex);
            }

            WriteToLog(String.Format("Action='GetFile';Status='TransferSuccess';LocalPath='{0}';RemotePath='{1}';FileAction='{1}'", localPath, remotePath, action));
        }
		internal void DispatchEvents (FileAction act, string filename, ref RenamedEventArgs renamed)
		{
			if (waiting) {
				lastData = new WaitForChangedResult ();
			}

			switch (act) {
			case FileAction.Added:
				lastData.Name = filename;
				lastData.ChangeType = WatcherChangeTypes.Created;
				OnCreated (new FileSystemEventArgs (WatcherChangeTypes.Created, path, filename));
				break;
			case FileAction.Removed:
				lastData.Name = filename;
				lastData.ChangeType = WatcherChangeTypes.Deleted;
				OnDeleted (new FileSystemEventArgs (WatcherChangeTypes.Deleted, path, filename));
				break;
			case FileAction.Modified:
				lastData.Name = filename;
				lastData.ChangeType = WatcherChangeTypes.Changed;
				OnChanged (new FileSystemEventArgs (WatcherChangeTypes.Changed, path, filename));
				break;
			case FileAction.RenamedOldName:
				if (renamed != null) {
					OnRenamed (renamed);
				}
				lastData.OldName = filename;
				lastData.ChangeType = WatcherChangeTypes.Renamed;
				renamed = new RenamedEventArgs (WatcherChangeTypes.Renamed, path, filename, "");
				break;
			case FileAction.RenamedNewName:
				lastData.Name = filename;
				lastData.ChangeType = WatcherChangeTypes.Renamed;
				if (renamed == null) {
					renamed = new RenamedEventArgs (WatcherChangeTypes.Renamed, path, "", filename);
				}
				OnRenamed (renamed);
				renamed = null;
				break;
			default:
				break;
			}
		}
示例#42
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="man"></param>
        /// <param name="action"></param>
        /// <param name="file1"></param>
        /// <param name="file2"></param>
        /// <returns></returns>
        public override bool OnFileAction(ManagerEngine man, FileAction action, IFile file1, IFile file2)
        {
            IFile thumbnailFolder, thumbnail;
            ManagerConfig config;

            switch (action) {
                case FileAction.Add:
                    config = file1.Config;

                    if (config.Get("upload.format") != null)
                        ImageUtils.FormatImage(file1.AbsolutePath, config.Get("upload.format"), config.GetInt("upload.autoresize_jpeg_quality", 90));

                    if (config.GetBool("upload.create_thumbnail", true))
                        thumbnail = this.MakeThumb(man, file1);

                    if (config.GetBool("upload.autoresize", false)) {
                        string ext = PathUtils.GetExtension(file1.Name).ToLower();
                        int newWidth, newHeight, configWidth, configHeight;
                        double scale;

                        // Validate format
                        if (ext != "gif" && ext != "jpeg" && ext != "jpg" && ext != "png")
                            return true;

                        MediaInfo imageInfo = new MediaInfo(file1.AbsolutePath);

                        configWidth = config.GetInt("upload.max_width", 1024);
                        configHeight = config.GetInt("upload.max_height", 768);

                        // Needs scaling?
                        if (imageInfo.Width > configWidth || imageInfo.Height > configHeight) {
                            scale = Math.Min(configWidth / (double) imageInfo.Width, configHeight / (double) imageInfo.Height);
                            newWidth = scale > 1 ? imageInfo.Width : (int) Math.Floor(imageInfo.Width * scale);
                            newHeight = scale > 1 ? imageInfo.Height : (int) Math.Floor(imageInfo.Height * scale);

                            ImageUtils.ResizeImage(file1.AbsolutePath, file1.AbsolutePath, newWidth, newHeight, config.GetInt("upload.autoresize_jpeg_quality", 90));
                        }
                    }

                    break;

                case FileAction.Delete:
                    config = file1.Config;

                    if (config.GetBool("thumbnail.delete", true)) {
                        thumbnailFolder = man.GetFile(file1.Parent, config["thumbnail.folder"]);
                        thumbnail = man.GetFile(thumbnailFolder.AbsolutePath, config.Get("thumbnail.prefix", "mcith") + file1.Name);

                        if (thumbnail.Exists)
                            thumbnail.Delete();

                        // Delete empty thumbnail folder
                        if (thumbnailFolder.Exists && thumbnailFolder.ListFiles().Length == 0)
                            thumbnailFolder.Delete();
                    }
                    break;
            }

            return true;
        }
示例#43
0
        public void ProcessData(CurrencyModel currency, CurrencyModel rank)
        {
            this.Text = SpecialIdentifierStringBuilder.ConvertScorpBotText(this.Text);

            this.Text = this.GetRegexEntries(this.Text, SFXRegexHeaderPattern, (string entry) =>
            {
                this.Actions.Add(new SoundAction(entry, 100));
                return(string.Empty);
            });

            int webRequestCount = 1;

            this.Text = this.GetRegexEntries(this.Text, ReadAPIRegexHeaderPattern, (string entry) =>
            {
                string si = "webrequest" + webRequestCount;
                this.Actions.Add(WebRequestAction.CreateForSpecialIdentifier(entry, si));
                webRequestCount++;
                return("$" + si);
            });

            if (this.Text.Contains("$toppoints("))
            {
                this.Text = SpecialIdentifierStringBuilder.ReplaceParameterVariablesEntries(this.Text, "$toppoints(", "$top", rank.SpecialIdentifier);
            }

            this.Text = this.Text.Replace("$points", "$" + rank.UserAmountSpecialIdentifier);
            this.Text = this.Text.Replace("$rank", "$" + rank.UserRankNameSpecialIdentifier);

            int readCount = 1;

            this.Text = this.GetRegexEntries(this.Text, ReadFileRegexHeaderPattern, (string entry) =>
            {
                string si = "read" + readCount;

                string[] splits   = entry.Split(new char[] { ',' });
                FileAction action = new FileAction(FileActionTypeEnum.ReadSpecificLineFromFile, si, splits[0]);
                if (splits.Length > 1)
                {
                    action.FileActionType = FileActionTypeEnum.ReadSpecificLineFromFile;
                    if (splits[1].Equals("first"))
                    {
                        action.LineIndexToRead = "1";
                    }
                    else if (splits[1].Equals("random"))
                    {
                        action.FileActionType = FileActionTypeEnum.ReadRandomLineFromFile;
                    }
                    else
                    {
                        action.LineIndexToRead = splits[1];
                    }
                }
                this.Actions.Add(action);

                readCount++;
                return("$" + si);
            });

            this.Text = this.GetRegexEntries(this.Text, WriteFileRegexHeaderPattern, (string entry) =>
            {
                string[] splits = entry.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                if (splits.Length == 1)
                {
                    this.Actions.Add(new FileAction(FileActionTypeEnum.AppendToFile, string.Empty, splits[0]));
                }
                else if (splits.Length == 2)
                {
                    this.Actions.Add(new FileAction(FileActionTypeEnum.AppendToFile, splits[1], splits[0]));
                }
                else if (splits.Length > 2)
                {
                    FileAction action = new FileAction(FileActionTypeEnum.AppendToFile, splits[1], splits[0]);
                    if (bool.TryParse(splits[2], out bool overwrite) && overwrite)
                    {
                        action.FileActionType = FileActionTypeEnum.SaveToFile;
                    }
                    this.Actions.Add(action);
                }
                return(string.Empty);
            });

            this.Actions.Add(new ChatAction(this.Text));
        }
示例#44
0
 private void DispatchFileAction(FileAction action)
 {
     DispatchFileAction(action, null);
 }
示例#45
0
 /// <summary>
 /// Uploads a local file specified in the path parameter to the remote FTP server.   
 /// </summary>
 /// <param name="localPath">Path to a file on the local machine.</param>
 /// <param name="remotePath">Filename or full path to file on the remote FTP server.</param>
 /// <param name="action">The type of put action taken.</param>
 /// <remarks>
 /// The file is uploaded to the current working directory on the remote server.  The remotePath
 /// parameter is used to specify the path and file name used to store the file on the remote server.
 /// Note that some FTP servers will not accept a full path.  On those systems you must navigate to
 /// the directory you wish to put the file using with the ChangeDirectory() or ChangeDirectoryMultiPath()
 /// method.
 /// </remarks>
 /// <seealso cref="PutFileAsync(string, string, FileAction)"/>
 /// <seealso cref="PutFileUnique(string)"/>
 /// <seealso cref="GetFile(string, string, FileAction)"/>
 /// <seealso cref="GetFileAsync(string, string, FileAction)"/>
 /// <seealso cref="MoveFile"/>
 /// <seealso cref="FxpCopy"/>
 /// <seealso cref="FxpCopyAsync"/>    
 public void PutFile(string localPath, string remotePath, FileAction action)
 {
     using (FileStream fileStream = File.OpenRead(localPath))
     {
         PutFile(fileStream, remotePath, action);
     }
 }
示例#46
0
        public static async Task <ICommandResult> File(DiscordUserMessageContext context, FileAction action, string filename = null)
        {
            switch (action)
            {
            case FileAction.Get:
                if (filename == null)
                {
                    return(new ErrorResult("Please provide a filename"));
                }
                if (!context.Bot.FileNames.Contains(filename))
                {
                    return(new ErrorResult("The provided filename was not a valid option"));
                }
                await context.Channel.SendFileAsync(Config.BasePath + filename);

                return(new SuccessResult());

            case FileAction.Put:
                if (filename == null)
                {
                    return(new ErrorResult("Please provide a filename"));
                }
                if (!context.Bot.FileNames.Contains(filename))
                {
                    return(new ErrorResult("The provided filename was not a valid option"));
                }
                if (context.Message.Attachments.Count == 0)
                {
                    return(new ErrorResult("Please attach a file with your message"));
                }
                var attachment = context.Message.Attachments.First();
                using (var fileStream = System.IO.File.Create(Config.BasePath + filename))
                {
                    await(await new HttpClient().GetStreamAsync(attachment.Url)).CopyToAsync(fileStream);
                }
                return(new SuccessResult("File successfully replaced"));

            case FileAction.List:
                return(new SuccessResult($"```\nAvailable Files:\n\n{string.Join("\n", context.Bot.FileNames)}\n```"));

            default:
                return(new ErrorResult("Unknown option"));
            }
        }
示例#47
0
        /// <summary>
        /// Uploads stream data specified in the inputStream parameter to the remote FTP server.   
        /// </summary>
        /// <param name="inputStream">Any open stream object on the local client machine.</param>
        /// <param name="remotePath">Filename or path and filename of the file stored on the remote FTP server.</param>
        /// <param name="action">The type of put action taken.</param>
        /// <remarks>
        /// The stream is uploaded to the current working directory on the remote server.  The remotePath
        /// parameter is used to specify the path and file name used to store the file on the remote server.
        /// Note that some FTP servers will not accept a full path.  On those systems you must navigate to
        /// the directory you wish to put the file using with the ChangeDirectory() or ChangeDirectoryMultiPath()
        /// method.
        /// </remarks>
        /// <seealso cref="PutFileAsync(string, string, FileAction)"/>
        /// <seealso cref="PutFileUnique(string)"/>
        /// <seealso cref="GetFile(string, string, FileAction)"/>
        /// <seealso cref="GetFileAsync(string, string, FileAction)"/>
        /// <seealso cref="MoveFile"/>
        /// <seealso cref="FxpCopy"/>
        /// <seealso cref="FxpCopyAsync"/>        
        public void PutFile(Stream inputStream, string remotePath, FileAction action)
        {
            if (inputStream == null)
                throw new ArgumentNullException("inputStream");

            if (!inputStream.CanRead)
                throw new ArgumentException("must be readable", "inputStream");

            if (remotePath == null)
                throw new ArgumentNullException("remotePath");

            if (remotePath.Length == 0)
                throw new ArgumentException("must contain a value", "remotePath");

            if (action == FileAction.None)
                throw new ArgumentOutOfRangeException("action", "must contain a value other than 'Unknown'");

            WriteToLog(String.Format("Action='PutFile';Status='TransferBegin';RemotePath='{0}';FileAction='{1}'", remotePath, action.ToString()));

            try
            {
                switch (action)
                {
                    case FileAction.CreateOrAppend:
                        base.TransferData(TransferDirection.ToServer, new FtpRequest(base.CharacterEncoding, FtpCmd.Appe, remotePath), inputStream);
                        break;
                    case FileAction.CreateNew:
                        if (Exists(remotePath))
                        {
                            throw new FtpException("Cannot overwrite existing file when action FileAction.CreateNew is specified.");
                        }
                        base.TransferData(TransferDirection.ToServer, new FtpRequest(base.CharacterEncoding, FtpCmd.Stor, remotePath), inputStream);
                        break;
                    case FileAction.Create:
                        base.TransferData(TransferDirection.ToServer, new FtpRequest(base.CharacterEncoding, FtpCmd.Stor, remotePath), inputStream);
                        break;
                    case FileAction.Resume:
                        //  get the size of the file already on the server (in bytes)
                        long remoteSize = GetFileSize(remotePath);

                        //  if the files are the same size then there is nothing to transfer
                        if (remoteSize == inputStream.Length)
                            return;

                        //  transfer file to the server
                        base.TransferData(TransferDirection.ToServer, new FtpRequest(base.CharacterEncoding, FtpCmd.Stor, remotePath), inputStream, remoteSize);
                        break;
                    case FileAction.ResumeOrCreate:
                        if (Exists(remotePath))
                            PutFile(inputStream, remotePath, FileAction.Resume);
                        else
                            PutFile(inputStream, remotePath, FileAction.Create);
                        break;
                }
            }
            catch (FtpException fex)
            {
                WriteToLog(String.Format("Action='PutFile';Status='TransferError';RemotePath='{0}';FileAction='{1}';ErrorMessage='{2}'", remotePath, action.ToString(), fex.Message));
                throw new FtpDataTransferException(String.Format("An error occurred while putting fileName '{0}'.", remotePath), base.LastResponse, fex);
            }

            WriteToLog(String.Format("Action='PutFile';Status='TransferSuccess';RemotePath='{0}';FileAction='{1}'", remotePath, action.ToString()));
        }
示例#48
0
        void ProcessEvents(byte [] buffer, int length)
        {
            ArrayList        newdirs = null;
            InotifyEvent     evt;
            int              nread   = 0;
            RenamedEventArgs renamed = null;

            while (length > nread)
            {
                int bytes_read = ReadEvent(buffer, nread, length, out evt);
                if (bytes_read <= 0)
                {
                    break;
                }

                nread += bytes_read;

                InotifyMask mask         = evt.Mask;
                bool        is_directory = (mask & InotifyMask.Directory) != 0;
                mask = (mask & Interesting);                 // Clear out all the bits that we don't need
                if (mask == 0)
                {
                    continue;
                }

                foreach (InotifyData data in GetEnumerator(requests [evt.WatchDescriptor]))
                {
                    ParentInotifyData parent = (ParentInotifyData)watches[data.FSW];

                    if (data == null || parent.Enabled == false)
                    {
                        continue;
                    }

                    string directory = data.Directory;
                    string filename  = evt.Name;
                    if (filename == null)
                    {
                        filename = directory;
                    }

                    FileSystemWatcher fsw    = data.FSW;
                    FileAction        action = 0;
                    if ((mask & (InotifyMask.Modify | InotifyMask.Attrib)) != 0)
                    {
                        action = FileAction.Modified;
                    }
                    else if ((mask & InotifyMask.Create) != 0)
                    {
                        action = FileAction.Added;
                    }
                    else if ((mask & InotifyMask.Delete) != 0)
                    {
                        action = FileAction.Removed;
                    }
                    else if ((mask & InotifyMask.DeleteSelf) != 0)
                    {
                        if (data.Watch != parent.data.Watch)
                        {
                            // To avoid duplicate events handle DeleteSelf only for the top level directory.
                            continue;
                        }
                        action = FileAction.Removed;
                    }
                    else if ((mask & InotifyMask.MoveSelf) != 0)
                    {
                        //action = FileAction.Removed;
                        continue;                         // Ignore this one
                    }
                    else if ((mask & InotifyMask.MovedFrom) != 0)
                    {
                        InotifyEvent to;
                        int          i = ReadEvent(buffer, nread, length, out to);
                        if (i == -1 || (to.Mask & InotifyMask.MovedTo) == 0 || evt.WatchDescriptor != to.WatchDescriptor)
                        {
                            action = FileAction.Removed;
                        }
                        else
                        {
                            nread  += i;
                            action  = FileAction.RenamedNewName;
                            renamed = new RenamedEventArgs(WatcherChangeTypes.Renamed, data.Directory, to.Name, evt.Name);
                            if (evt.Name != data.Directory && !fsw.Pattern.IsMatch(evt.Name))
                            {
                                filename = to.Name;
                            }
                        }
                    }
                    else if ((mask & InotifyMask.MovedTo) != 0)
                    {
                        action = FileAction.Added;
                    }
                    if (fsw.IncludeSubdirectories)
                    {
                        string full    = fsw.FullPath;
                        string datadir = data.Directory;
                        if (datadir != full)
                        {
                            int len   = full.Length;
                            int slash = 1;
                            if (len > 1 && full [len - 1] == Path.DirectorySeparatorChar)
                            {
                                slash = 0;
                            }
                            string reldir = datadir.Substring(full.Length + slash);
                            datadir  = Path.Combine(datadir, filename);
                            filename = Path.Combine(reldir, filename);
                        }
                        else
                        {
                            datadir = Path.Combine(full, filename);
                        }

                        if (action == FileAction.Added && is_directory)
                        {
                            if (newdirs == null)
                            {
                                newdirs = new ArrayList(2);
                            }

                            InotifyData fd = new InotifyData();
                            fd.FSW       = fsw;
                            fd.Directory = datadir;
                            newdirs.Add(fd);
                        }

                        if (action == FileAction.RenamedNewName && is_directory)
                        {
                            string renamedOldFullPath       = renamed.OldFullPath;
                            string renamedFullPath          = renamed.FullPath;
                            int    renamedOldFullPathLength = renamedOldFullPath.Length;

                            foreach (InotifyData child in parent.children)
                            {
                                if (child.Directory.StartsWith(renamedOldFullPath
#if NET_2_0
                                                               , StringComparison.Ordinal
#endif
                                                               ))
                                {
                                    child.Directory = renamedFullPath +
                                                      child.Directory.Substring(renamedOldFullPathLength);
                                }
                            }
                        }
                    }

                    if (action == FileAction.Removed && filename == data.Directory)
                    {
                        int idx = parent.children.IndexOf(data);
                        if (idx != -1)
                        {
                            parent.children.RemoveAt(idx);
                            if (!fsw.Pattern.IsMatch(Path.GetFileName(filename)))
                            {
                                continue;
                            }
                        }
                    }

                    if (filename != data.Directory && !fsw.Pattern.IsMatch(Path.GetFileName(filename)))
                    {
                        continue;
                    }

                    lock (fsw) {
                        fsw.DispatchEvents(action, filename, ref renamed);
                        if (action == FileAction.RenamedNewName)
                        {
                            renamed = null;
                        }
                        if (fsw.Waiting)
                        {
                            fsw.Waiting = false;
                            System.Threading.Monitor.PulseAll(fsw);
                        }
                    }
                }
            }

            if (newdirs != null)
            {
                foreach (InotifyData newdir in newdirs)
                {
                    try {
                        StartMonitoringDirectory(newdir, true);
                        AppendRequestData(newdir);
                        ((ParentInotifyData)watches[newdir.FSW]).children.Add(newdir);
                    } catch {}                     // ignore the given directory
                }
                newdirs.Clear();
            }
        }
示例#49
0
 public Action(FileAction fileAction)
 {
     Type = fileAction.FixedType.ToString();
 }
示例#50
0
 public void Enqueue(FileAction file)
 {
     _queue.Enqueue(file);
     Task.Run(() => NotifyObservers());
 }
 internal FileChangeEvent(FileAction action, string fileName)
 {
     this.Action = action;
     this.FileName = fileName;
 }
示例#52
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="action"></param>
 public void DispatchFileAction(FileAction action)
 {
     DispatchFileAction(action, null);
 }
示例#53
0
文件: Plugin.cs 项目: nhtera/CrowdCMS
 /// <summary>
 ///  Gets called before a file action occurs for example before a rename or copy.
 /// </summary>
 /// <param name="man">ManagerEngine reference that the plugin is assigned to.</param>
 /// <param name="action">File action type.</param>
 /// <param name="file1">File object 1 for example from in a copy operation.</param>
 /// <param name="file2">File object 2 for example to in a copy operation. Might be null in for example a delete.</param>
 /// <returns>true/false if the execution of the event chain should continue execution.</returns>
 public virtual bool OnBeforeFileAction(ManagerEngine man, FileAction action, IFile file1, IFile file2)
 {
     return true;
 }
 public FileActionControl(ActionContainerControl containerControl, FileAction action) : this(containerControl) { this.action = action; }
示例#55
0
        void ProcessEvents()
        {
            ArrayList newdirs = null;

            lock (this)
            {
                do
                {
                    int               code;
                    string            filename;
                    int               requestNumber;
                    FileSystemWatcher fsw;

                    if (InternalFAMNextEvent(ref conn, out filename,
                                             out code, out requestNumber) != 1)
                    {
                        return;
                    }

                    bool found = false;
                    switch ((FAMCodes)code)
                    {
                    case FAMCodes.Changed:
                    case FAMCodes.Deleted:
                    case FAMCodes.Created:
                        found = requests.ContainsKey(requestNumber);
                        break;

                    case FAMCodes.Moved:
                    case FAMCodes.StartExecuting:
                    case FAMCodes.StopExecuting:
                    case FAMCodes.Acknowledge:
                    case FAMCodes.Exists:
                    case FAMCodes.EndExist:
                    default:
                        found = false;
                        break;
                    }

                    if (!found)
                    {
                        continue;
                    }

                    FAMData data = (FAMData)requests [requestNumber];
                    if (!data.Enabled)
                    {
                        continue;
                    }

                    fsw = data.FSW;
                    NotifyFilters    flt     = fsw.NotifyFilter;
                    RenamedEventArgs renamed = null;
                    FileAction       fa      = 0;
                    if (code == (int)FAMCodes.Changed && (flt & changed) != 0)
                    {
                        fa = FileAction.Modified;
                    }
                    else if (code == (int)FAMCodes.Deleted)
                    {
                        fa = FileAction.Removed;
                    }
                    else if (code == (int)FAMCodes.Created)
                    {
                        fa = FileAction.Added;
                    }

                    if (fa == 0)
                    {
                        continue;
                    }

                    if (fsw.IncludeSubdirectories)
                    {
                        string full    = fsw.FullPath;
                        string datadir = data.Directory;
                        if (datadir != full)
                        {
                            int len   = full.Length;
                            int slash = 1;
                            if (len > 1 && full [len - 1] == Path.DirectorySeparatorChar)
                            {
                                slash = 0;
                            }
                            string reldir = datadir.Substring(full.Length + slash);
                            datadir  = Path.Combine(datadir, filename);
                            filename = Path.Combine(reldir, filename);
                        }
                        else
                        {
                            datadir = Path.Combine(full, filename);
                        }

                        if (fa == FileAction.Added && Directory.Exists(datadir))
                        {
                            if (newdirs == null)
                            {
                                newdirs = new ArrayList(4);
                            }

                            FAMData fd = new FAMData();
                            fd.FSW            = fsw;
                            fd.Directory      = datadir;
                            fd.FileMask       = fsw.MangledFilter;
                            fd.IncludeSubdirs = true;
                            fd.SubDirs        = new Hashtable();
                            fd.Enabled        = true;
                            newdirs.Add(fd);
                            newdirs.Add(data);
                        }
                    }

                    if (filename != data.Directory && !fsw.Pattern.IsMatch(filename))
                    {
                        continue;
                    }

                    lock (fsw)
                    {
                        fsw.DispatchEvents(fa, filename, ref renamed);
                        if (fsw.Waiting)
                        {
                            fsw.Waiting = false;
                            System.Threading.Monitor.PulseAll(fsw);
                        }
                    }
                }while (FAMPending(ref conn) > 0);
            }


            if (newdirs != null)
            {
                int count = newdirs.Count;
                for (int n = 0; n < count; n += 2)
                {
                    FAMData newdir = (FAMData)newdirs [n];
                    FAMData parent = (FAMData)newdirs [n + 1];
                    StartMonitoringDirectory(newdir, true);
                    requests [newdir.Request.ReqNum] = newdir;
                    lock (parent)
                    {
                        parent.SubDirs [newdir.Directory] = newdir;
                    }
                }
                newdirs.Clear();
            }
        }
示例#56
0
            public void RepFile()
            {
                try {
                    List <string> list = FileAction.ReadToArr(file.FullName);
                    string        p    = file.FullName.Replace(path, outpath);

                    // 匹配注释正则
                    string regNotes = "([/]{2,}|[*]+).*";
                    // 匹配中文正则
                    string regChinese = @"([\u4e00-\u9fa5]{1,}[\s,,‘“;(()):、:.&\\-a-zA-Z0-9\u4e00-\u9fa5]{0,}[。”’!0-9\u4e00-\u9fa5]{1,})|([\u4e00-\u9fa5]{1})";
                    int    index      = 0;

                    foreach (var item in list)
                    {
                        index++;
                        // 去掉注释
                        string str = DataCheck.RepStr(item.Trim(), regNotes, "");
                        //是否包含中文
                        if (!DataCheck.CheckReg(str, regChinese))
                        {
                            FileAction.AppendStr(p, item + "\n");
                        }
                        else
                        {
                            // 取出中文
                            string[] strArr = DataCheck.GetRegStrArr(str, regChinese);
                            string   temp   = str;
                            string   get    = "";
                            // 在语言包中寻找匹配
                            foreach (var chinese in strArr)
                            {
                                // 如果没有包含汉字,查找下一个
                                if (!DataCheck.CheckReg(chinese, "[\u4e00-\u9fa5]+"))
                                {
                                    continue;
                                }

                                // 若语言包中存在对应中文,直接替换
                                if (dic.ContainsKey(chinese))
                                {
                                    get  = dic[chinese];
                                    temp = temp.Replace(chinese, DataCheck.RepLanguage(dic[chinese], false));
                                    errInfo.Add($"{chinese}\t{dic[chinese]}\t{file.FullName}");
                                }
                                // 否则,去寻找最类似的中文
                                else
                                {
                                    // 获取极限长度
                                    int min = chinese.Length - 2;
                                    int max = chinese.Length + 2;
                                    // 判断是否替换
                                    bool bl = false;
                                    // 循环字典
                                    foreach (var key in dic.Keys)
                                    {
                                        // 超出极限长度,则跳出
                                        if (max < key.Length || key.Length < min)
                                        {
                                            continue;
                                        }
                                        // 若符合极限长度,且包含当前文字
                                        if (key.Contains(chinese))
                                        {
                                            // 进行替换
                                            temp = temp.Replace(chinese, DataCheck.RepLanguage(dic[key], false));
                                            errInfo.Insert(0, $"^{chinese}:{index}行\t{dic[key]}\t{file.FullName}");
                                            bl = true;
                                        }
                                    }
                                    if (!bl)
                                    {
                                        errInfo.Insert(0, $"^^{chinese}:{index}行\t{file.FullName}");
                                    }
                                }
                            }

                            // 将当前行写入文件
                            FileAction.AppendStr(p, item.Replace(str, temp) + "\n");
                        }
                    }
                }
                catch (Exception e) {
                    errInfo.Add("错误:" + file.FullName + "\t" + e.Message);
                }
            }
 public virtual void registerFileAction(FileAction action)
 {
     this.mFileAction = action;
 }
示例#58
0
 public void trySelectFile()
 {
     _queuedAction = FileAction.Select;
 }
示例#59
0
        private void ProcessEvents(byte[] buffer, int length)
        {
            ArrayList        arrayList        = null;
            int              num              = 0;
            RenamedEventArgs renamedEventArgs = null;

            while (length > num)
            {
                InotifyEvent inotifyEvent;
                int          num2 = InotifyWatcher.ReadEvent(buffer, num, length, out inotifyEvent);
                if (num2 <= 0)
                {
                    break;
                }
                num += num2;
                InotifyMask inotifyMask = inotifyEvent.Mask;
                bool        flag        = (inotifyMask & InotifyMask.Directory) != (InotifyMask)0u;
                inotifyMask &= InotifyWatcher.Interesting;
                if (inotifyMask != (InotifyMask)0u)
                {
                    foreach (object obj in InotifyWatcher.GetEnumerator(InotifyWatcher.requests[inotifyEvent.WatchDescriptor]))
                    {
                        InotifyData       inotifyData       = (InotifyData)obj;
                        ParentInotifyData parentInotifyData = (ParentInotifyData)InotifyWatcher.watches[inotifyData.FSW];
                        if (inotifyData != null && parentInotifyData.Enabled)
                        {
                            string directory = inotifyData.Directory;
                            string text      = inotifyEvent.Name;
                            if (text == null)
                            {
                                text = directory;
                            }
                            FileSystemWatcher fsw        = inotifyData.FSW;
                            FileAction        fileAction = (FileAction)0;
                            if ((inotifyMask & (InotifyMask.Modify | InotifyMask.Attrib)) != (InotifyMask)0u)
                            {
                                fileAction = FileAction.Modified;
                            }
                            else if ((inotifyMask & InotifyMask.Create) != (InotifyMask)0u)
                            {
                                fileAction = FileAction.Added;
                            }
                            else if ((inotifyMask & InotifyMask.Delete) != (InotifyMask)0u)
                            {
                                fileAction = FileAction.Removed;
                            }
                            else if ((inotifyMask & InotifyMask.DeleteSelf) != (InotifyMask)0u)
                            {
                                if (inotifyData.Watch != parentInotifyData.data.Watch)
                                {
                                    continue;
                                }
                                fileAction = FileAction.Removed;
                            }
                            else
                            {
                                if ((inotifyMask & InotifyMask.MoveSelf) != (InotifyMask)0u)
                                {
                                    continue;
                                }
                                if ((inotifyMask & InotifyMask.MovedFrom) != (InotifyMask)0u)
                                {
                                    InotifyEvent inotifyEvent2;
                                    int          num3 = InotifyWatcher.ReadEvent(buffer, num, length, out inotifyEvent2);
                                    if (num3 == -1 || (inotifyEvent2.Mask & InotifyMask.MovedTo) == (InotifyMask)0u || inotifyEvent.WatchDescriptor != inotifyEvent2.WatchDescriptor)
                                    {
                                        fileAction = FileAction.Removed;
                                    }
                                    else
                                    {
                                        num             += num3;
                                        fileAction       = FileAction.RenamedNewName;
                                        renamedEventArgs = new RenamedEventArgs(WatcherChangeTypes.Renamed, inotifyData.Directory, inotifyEvent2.Name, inotifyEvent.Name);
                                        if (inotifyEvent.Name != inotifyData.Directory && !fsw.Pattern.IsMatch(inotifyEvent.Name))
                                        {
                                            text = inotifyEvent2.Name;
                                        }
                                    }
                                }
                                else if ((inotifyMask & InotifyMask.MovedTo) != (InotifyMask)0u)
                                {
                                    fileAction = FileAction.Added;
                                }
                            }
                            if (fsw.IncludeSubdirectories)
                            {
                                string fullPath = fsw.FullPath;
                                string text2    = inotifyData.Directory;
                                if (text2 != fullPath)
                                {
                                    int length2 = fullPath.Length;
                                    int num4    = 1;
                                    if (length2 > 1 && fullPath[length2 - 1] == Path.DirectorySeparatorChar)
                                    {
                                        num4 = 0;
                                    }
                                    string path = text2.Substring(fullPath.Length + num4);
                                    text2 = Path.Combine(text2, text);
                                    text  = Path.Combine(path, text);
                                }
                                else
                                {
                                    text2 = Path.Combine(fullPath, text);
                                }
                                if (fileAction == FileAction.Added && flag)
                                {
                                    if (arrayList == null)
                                    {
                                        arrayList = new ArrayList(2);
                                    }
                                    arrayList.Add(new InotifyData
                                    {
                                        FSW       = fsw,
                                        Directory = text2
                                    });
                                }
                                if (fileAction == FileAction.RenamedNewName && flag)
                                {
                                    string oldFullPath = renamedEventArgs.OldFullPath;
                                    string fullPath2   = renamedEventArgs.FullPath;
                                    int    length3     = oldFullPath.Length;
                                    foreach (object obj2 in parentInotifyData.children)
                                    {
                                        InotifyData inotifyData2 = (InotifyData)obj2;
                                        if (inotifyData2.Directory.StartsWith(oldFullPath, StringComparison.Ordinal))
                                        {
                                            inotifyData2.Directory = fullPath2 + inotifyData2.Directory.Substring(length3);
                                        }
                                    }
                                }
                            }
                            if (fileAction == FileAction.Removed && text == inotifyData.Directory)
                            {
                                int num5 = parentInotifyData.children.IndexOf(inotifyData);
                                if (num5 != -1)
                                {
                                    parentInotifyData.children.RemoveAt(num5);
                                    if (!fsw.Pattern.IsMatch(Path.GetFileName(text)))
                                    {
                                        continue;
                                    }
                                }
                            }
                            if (!(text != inotifyData.Directory) || fsw.Pattern.IsMatch(Path.GetFileName(text)))
                            {
                                FileSystemWatcher obj3 = fsw;
                                lock (obj3)
                                {
                                    fsw.DispatchEvents(fileAction, text, ref renamedEventArgs);
                                    if (fileAction == FileAction.RenamedNewName)
                                    {
                                        renamedEventArgs = null;
                                    }
                                    if (fsw.Waiting)
                                    {
                                        fsw.Waiting = false;
                                        System.Threading.Monitor.PulseAll(fsw);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (arrayList != null)
            {
                foreach (object obj4 in arrayList)
                {
                    InotifyData inotifyData3 = (InotifyData)obj4;
                    try
                    {
                        InotifyWatcher.StartMonitoringDirectory(inotifyData3, true);
                        InotifyWatcher.AppendRequestData(inotifyData3);
                        ((ParentInotifyData)InotifyWatcher.watches[inotifyData3.FSW]).children.Add(inotifyData3);
                    }
                    catch
                    {
                    }
                }
                arrayList.Clear();
            }
        }
示例#60
0
 internal NotificationQueueItem(FileChangeEventHandler callback, FileAction action, string filename)
 {
     this.Callback = callback;
     this.Action   = action;
     this.Filename = filename;
 }