Thứ Sáu, 22 tháng 7, 2016

BackgroundWorker utilities helper

BackgroundWorker utilities

Manual usage:
Register events and execute DoWork()

_bgHelper.AddDoWork(OnDowork).AddRunWorkerCompleted(OnCompleted)
    .AddReportProgressChanged(OnReportProgress).SupportCancellation().DoWork();

BackgroundWorker events

private void OnDowork(object sender, DoWorkEventArgs e)
{
    if (_bgHelper.CancellationPending)
    {
        e.Cancel = true;
        return;
    }
    //TODO: Working progress
}
private void OnReportProgress(object sender, ProgressChangedEventArgs e)
{
    //TODO: Report progress on working
}
private void OnCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    //TODO: Working completed
}

using System;
using System.ComponentModel;
 
namespace App.Helpers
{
    /// <summary>
    /// Class BackgroundWorkerHelper.
    /// Support execute action on background thread
    /// </summary>
    public class BackgroundWorkerHelper : IDisposable
    {
        #region Private variable
        /// <summary>
        /// The _added event do work
        /// </summary>
        private bool _addedEventDoWork;
        /// <summary>
        /// The _added event run worker completed
        /// </summary>
        private bool _addedEventRunWorkerCompleted;
        /// <summary>
        /// The _worker
        /// </summary>
        private BackgroundWorker _worker;
 
        /// <summary>
        /// The _on do work event handler
        /// </summary>
        private DoWorkEventHandler _onDoWorkEventHandler;
        /// <summary>
        /// The _on report progress changed
        /// </summary>
        private ProgressChangedEventHandler _onReportProgressChanged;
        /// <summary>
        /// The _on completed event handler
        /// </summary>
        private RunWorkerCompletedEventHandler _onCompletedEventHandler;
 
        public bool CancellationPending
        {
            get
            {
                return _worker != null && _worker.CancellationPending;
            }
        }
        #endregion
 
        #region Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="BackgroundWorkerHelper"/> class.
        /// </summary>
        public BackgroundWorkerHelper() : this(new BackgroundWorker())
        {
 
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="BackgroundWorkerHelper"/> class.
        /// </summary>
        /// <param name="worker">The worker.</param>
        public BackgroundWorkerHelper(BackgroundWorker worker)
        {
            _worker = worker;
        }
        #endregion
 
        #region Public functions
        /// <summary>
        /// Adds the DoWork event.
        /// </summary>
        /// <param name="onDoWorkEvent">The on do work event.</param>
        /// <returns>BackgroundWorkerHelper.</returns>
        public BackgroundWorkerHelper AddDoWork(DoWorkEventHandler onDoWorkEvent)
        {
            ReleaseEventHandler(); //Remove dupplicate event handler
            _addedEventDoWork = true;
            _onDoWorkEventHandler = onDoWorkEvent;
            _worker.DoWork += OnDoWork;
            return this;
        }
 
        /// <summary>
        /// Adds the ReportProgressChanged event.
        /// </summary>
        /// <param name="onReportProgressChanged">The on report progress changed.</param>
        /// <returns>BackgroundWorkerHelper.</returns>
        public BackgroundWorkerHelper AddReportProgressChanged(ProgressChangedEventHandler onReportProgressChanged)
        {
            _worker.WorkerReportsProgress = true;
            _onReportProgressChanged = onReportProgressChanged;
            _worker.ProgressChanged += OnProgressChanged;
            return this;
        }
 
        /// <summary>
        /// Adds the RunWorkerCompleted event.
        /// </summary>
        /// <param name="onRunWorkerCompleted">The on run worker completed.</param>
        /// <returns>BackgroundWorkerHelper.</returns>
        public BackgroundWorkerHelper AddRunWorkerCompleted(RunWorkerCompletedEventHandler onRunWorkerCompleted)
        {
            _addedEventRunWorkerCompleted = true;
            _onCompletedEventHandler = onRunWorkerCompleted;
            return this;
        }
 
        /// <summary>
        /// Supports the cancellation.
        /// </summary>
        /// <returns>BackgroundWorkerHelper.</returns>
        public BackgroundWorkerHelper SupportCancellation()
        {
            _worker.WorkerSupportsCancellation = true;
            return this;
        }
 
        /// <summary>
        /// Does the work.
        /// </summary>
        /// <param name="obj">The object.</param>
        public void DoWork(object obj = null)
        {
            if (_addedEventDoWork)
            {
                _worker.RunWorkerCompleted += OnRunWorkerCompleted;
                _worker.RunWorkerAsync(obj);
            }
        }
 
        /// <summary>
        /// Cancels this instance.
        /// </summary>
        public void Cancel()
        {
            if (_worker.WorkerSupportsCancellation)
            {
                if (_worker.IsBusy)
                {
                    _worker.CancelAsync();
                }
 
                //Release all event handler when cancel
                ReleaseEventHandler();
            }
        }
 
        /// <summary>
        /// Determines whether this instance is busy.
        /// </summary>
        /// <returns><c>true</c> if this instance is busy; otherwise, <c>false</c>.</returns>
        public bool IsBusy()
        {
            return _worker != null && _worker.IsBusy;
        }
        #endregion
 
        #region Private functions
        /// <summary>
        /// Handles the <see cref="E:DoWork" /> event.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="args">The <see cref="DoWorkEventArgs"/> instance containing the event data.</param>
        private void OnDoWork(object sender, DoWorkEventArgs args)
        {
            _onDoWorkEventHandler(sender, args);
        }
        /// <summary>
        /// Handles the <see cref="E:ProgressChanged" /> event.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="args">The <see cref="ProgressChangedEventArgs"/> instance containing the event data.</param>
        private void OnProgressChanged(object sender, ProgressChangedEventArgs args)
        {
            _onReportProgressChanged(sender, args);
        }
        /// <summary>
        /// Handles the <see cref="E:RunWorkerCompleted" /> event.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="args">The <see cref="RunWorkerCompletedEventArgs"/> instance containing the event data.</param>
        private void OnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs args)
        {
            if (args.Error != null)
            {
                //TODO: Write Error Log
            }
            if (_onCompletedEventHandler != null)
            {
                _onCompletedEventHandler(sender, args);
            }
            //Release all registered event handler when completed
            ReleaseEventHandler();
        }
        /// <summary>
        /// Releases the event handler.
        /// </summary>
        private void ReleaseEventHandler()
        {
            if (_addedEventDoWork)
            {
                _worker.DoWork -= OnDoWork;
                _onDoWorkEventHandler = null;
                _addedEventDoWork = false;
            }
            if (_worker.WorkerReportsProgress)
            {
                _worker.ProgressChanged -= OnProgressChanged;
                _onReportProgressChanged = null;
                _worker.WorkerReportsProgress = false;
            }
            if (_addedEventRunWorkerCompleted)
            {
                _worker.RunWorkerCompleted -= OnRunWorkerCompleted;
                _onCompletedEventHandler = null;
                _addedEventRunWorkerCompleted = false;
            }
        }
        #endregion
 
        #region Disposable
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
 
        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_worker != null)
                {
                    _worker.Dispose();
                    _worker = null;
                }
            }
        }
        ~BackgroundWorkerHelper()
        {
            Dispose(false);
        }
        #endregion
    }
}

Thứ Tư, 15 tháng 6, 2016

[YoutubeVideoDownloader] Download youtube video with multiple progress and multiple links

Main function:

  1. Add Link: Add single Youtube video link
  2. Import Source: Add multiple link from text (*.txt) or excel file (*.xlsx)
  3. Action: Support cancel download selected link or cancel all
  4. Context menu(right click): function when right click on list video link
  5. Help>Manual: Manual usage the program

1. Main Screen

2. Add Link Screen

3. Import Source Screen

Use library: https://github.com/jamesqo/libvideo to extract link
Download Link: YoutubeVideoDownloader_2016.rar

Thứ Năm, 11 tháng 6, 2015

[PARSER] Parse folder and files to treeview structure on text file

Input: Directory Path
Output: Return string treeview structure

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ParserUtils
{
    /// 
    /// Class FileFolderToText.
    /// Parser folder and file structure to text file.
    /// 
    public class FileFolderToText
    {
        Dictionary<stringint> dictCounterType = new Dictionary<stringint>(StringComparer.OrdinalIgnoreCase)
        {
            {"Others"0}
        };
        private string _otherExtension = string.Empty;
        private int _totalFile = 0;
        private int _totalFolder = 0;
        Dictionary<stringstring> dicMapFileType = new Dictionary<stringstring>(StringComparer.OrdinalIgnoreCase)
        {
            {".doc""Word"},
            {".docx""Word"},
            {".xls""Excel File"},
            {".xlsx""Excel File"},
            {".xml""Xml File"},
            {".xsd""Xsd File"},
            {".ppt""Power Point File"},
            {".pptx""Power Point File"},
            {".mdb""Access File"},
            {".mpp""Microsoft Project File"},
            {".pdf""Pdf File"},
            {".png""Image File"},
            {".gif""Image File"},
            {".jpg""Image File"},
            {".jpeg""ImageFile"},
            {".bmp""Image File"},
            {".txt""Text File"},
            {".zip""Zip File"},
            {".rar""Rar File"},
            {".7z""7Z File"},
            {".mht""Html Document"},
            {".html""Html File"},
            {".htm""Html File"},
            {".exe""Execute File"},
            {".ssc""DScript File"},
            {".ini""INI File"},
            {".inf""INF File"},
            {".bat""BAT File"},
            {".scc""Source Control File"},
            {".vsd""Visio File"},
            {".csv""CSV File"},
            {".cs""CSharp File"},
            {".vb""VB File"},
            {".java""Java File"},
            {".jsp""JSP File"},
            {".diff""Diffrent File"},
            {".resx""Resource File"},
            {".json""JSON File"},
            {".rtf""RTF File"},
            {".rb""Rubby File"},
            {".mp3""MP3 File"},
            {".mp4""MP4 File"},
            {".ico""Icon File"}
        };

        private string _folderPath = string.Empty;
        public FileFolderToText(string folderPath)
        {
            _folderPath = folderPath;
        }
        public bool Save(string filePath, string data = null)
        {
            if (data == null)
                data = ToText(_folderPath);
            try
            {
                using (StreamWriter sw = new StreamWriter(filePath, falseEncoding.GetEncoding(932)))
                {
                    sw.WriteLine("=======================");
                    sw.WriteLine(string.Format("Folder Path: {0}", _folderPath));
                    sw.WriteLine(string.Format("Total: {0} folder and {1} files.", _totalFolder, _totalFile));
                    sw.WriteLine("========Summary=========");
                    sw.WriteLine(_otherExtension);
                    foreach (var dict in dictCounterType)
                    {
                        sw.WriteLine(string.Format("Total: {0} {1} files.", dict.Value, dict.Key));
                    }
                    sw.WriteLine("=======================");
                    sw.Write(data);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// 
        /// Parse folder and files to the text.
        /// 
        /// "folderPath">The folder path.
        /// "indent">The space indent.
        /// System.String text tree structure.
        private string ToText(string folderPath, int indent = 0)
        {
            StringBuilder sb = new StringBuilder();
            DirectoryInfo dirInfo = new DirectoryInfo(folderPath);
            if (dirInfo != null)
            {
                _totalFolder++;
                sb.Append(string.Empty.PadLeft(indent));
                sb.AppendLine(dirInfo.Name);
                DirectoryInfo[] lstDirInfo = dirInfo.GetDirectories();
                if (lstDirInfo.Length > 0)
                {
                    for (int i = 0; i < lstDirInfo.Length; i++)
                    {
                        sb.Append(ToText(lstDirInfo[i].FullName, indent + 4));
                    }
                }
                FileInfo[] lstFileInfo = dirInfo.GetFiles();
                if (lstFileInfo.Length > 0)
                {
                    for (int i = 0; i < lstFileInfo.Length; i++)
                    {
                        MappingFileType(Path.GetExtension(lstFileInfo[i].Name));
                        _totalFile++;
                        sb.Append(string.Empty.PadLeft(indent + 4));
                        sb.AppendLine(lstFileInfo[i].Name);
                    }
                }
            }
            return sb.ToString();
        }
        private void MappingFileType(string ext)
        {
            if (dicMapFileType.ContainsKey(ext))
            {
                if (dictCounterType.ContainsKey(dicMapFileType[ext]))
                    dictCounterType[dicMapFileType[ext]]++;
                else
                    dictCounterType[dicMapFileType[ext]] = 1;
            }
            else
            {
                dictCounterType["Others"]++;
                if (_otherExtension.Length == 0)
                {
                    _otherExtension += ext;
                }
                else if (_otherExtension.IndexOf(ext) == -1)
                {
                    _otherExtension += "|" + ext;
                }
            }
        }
    }
}

Execute:

FileFolderToText parseStructure = new FileFolderToText(@"D:\Develop");

parseStructure.Save(@"C:\OutputFile.txt");