Ejemplo n.º 1
0
        ///<summary>
        /// Handles the various progress actions
        ///</summary>
        public bool Update(object o, ProgressAction action)
        {
            if (action == ProgressAction.Hide)
            {
                this.Visible = false;
                return(false);
            }
            else if (action == ProgressAction.Show)
            {
                this.Visible = true;
                return(false);
            }
            else if (action == ProgressAction.Message)
            {
                ProgressBar.Text = (string)o;
                return(false);
            }
            else if (action == ProgressAction.Destroy)
            {
                this.Destroy();
                return(false);
            }

            ProgressBar.Fraction = (double)o;

            if (cancelClicked == true)
            {
                cancelClicked = false;
                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 2
0
 void OnChanged(ProgressAction pa)
 {
     if (Changed != null)
     {
         Changed(this, new ProgressArgs(pa));
     }
 }
Ejemplo n.º 3
0
        /// <summary>
        ///		Añade una tarea a la cola y la ejecuta
        /// </summary>
        public void Process(AbstractTask processor)
        {
            Task task;

            // Añade el procesador a la cola
            Queue.Add(processor);
            // Asigna los manejador de eventos
            processor.ActionProcess  += (sender, evntArgs) => ActionProcess?.Invoke(sender, evntArgs);
            processor.Progress       += (sender, evntArgs) => Progress?.Invoke(sender, evntArgs);
            processor.ProgressAction += (sender, evntArgs) => ProgressAction?.Invoke(sender, evntArgs);
            processor.EndProcess     += (sender, evntArgs) => TreatEndProcess(sender as AbstractTask, evntArgs);
            // Crea la tarea para la compilación en otro hilo
            task = new Task(() => processor.Process());
            // Arranca la tarea de generación
            try
            {
                task.Start();
            }
            catch (Exception exception)
            {
                TreatEndProcess(processor,
                                new EventArguments.EndProcessEventArgs($"Error al lanzar el proceso{Environment.NewLine}{exception.Message}",
                                                                       new List <string> {
                    exception.Message
                }));
            }
        }
Ejemplo n.º 4
0
 public void UpdateProgress(ProgressAction action, int progress)
 {
     if (this.action != action || this.progress != progress)
     {
         this.action   = action;
         this.progress = progress;
         ProgressChanged?.Invoke(action, progress);
     }
 }
        void ManageDiagrams(TimeRow row, double epsilon, ref Image diagramRasterized, ref Image diagramDistance, ref Image scaleDistance, ref Chart pointDiagram, ref Chart lineDiagram, ref string AnalysisResult)
        {
            DiagramManager diagram = new DiagramManager(row, (float)epsilon);

            diagram.GenerateReccurentMatrix();
            diagramRasterized = diagram.GetReccurentDiagram(_view.DiagramBox.Width, _view.DiagramBox.Height);
            diagramDistance   = diagram.GetDistanceDiagram(_view.DistanceBox.Width, _view.DistanceBox.Height);
            scaleDistance     = diagram.GetDistancePalette(_view.DistanceScaleBox.Width);

            bool[,] matrix = diagram.GetReccurentMatrix();

            int side = matrix.GetLength(0);

            pointDiagram.Series[0].MarkerSize = side > 100 ? 2 : (int)(pointDiagram.Height / side * 0.9);
            pointDiagram.Series[0].Points.Clear();

            int move      = 0;
            int max       = side * side + row.Row.Length - 1;
            int invokeVal = max / 10;

            for (int i = 0; i < side; i++)
            {
                for (int j = 0; j < side; j++)
                {
                    if (matrix[i, j] == true)
                    {
                        pointDiagram.Series[0].Points.AddXY(i + 1, j + 1);
                    }
                    if ((move % invokeVal) == 0)
                    {
                        ProgressAction?.Invoke(10, move / invokeVal);
                    }
                    move++;
                }
            }

            lineDiagram.Series[0].Points.Clear();
            for (int i = 0; i < row.Row.Length - 1; i++)
            {
                lineDiagram.Series[0].Points.AddXY((row[i]), row[i + 1]);
                if ((move % invokeVal) == 0)
                {
                    ProgressAction?.Invoke(10, move / invokeVal);
                }
                move++;
            }
            //if (move < max) ProgressAction?.Invoke(10, move / invokeVal);

            AnalysisResult = "\n Analysis: \n RR: " + diagram.RR.ToString() + "\n DET: " + diagram.DET.ToString() +
                             "\n L: " + diagram.L.ToString() + "\n DIV: " + diagram.DIV.ToString() +
                             "\n ENTR: " + diagram.ENTR.ToString() + "\n RATIO: " + diagram.RATIO.ToString();

            row.Dispose();
            diagram.Dispose();
            matrix = null;
            GC.Collect();
        }
Ejemplo n.º 6
0
        private static void ExecuteWorker(object o)
        {
            ProgressAction action = o as ProgressAction;

            if (action != null)
            {
                action.Execute();
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Uploads a file using FTP.
        /// </summary>
        /// <param name="localFilePath">The local path to the file which will be uploaded.</param>
        /// <param name="pathOnServer">The path on the server to upload the file to.</param>
        /// <param name="progressAction">Is called when the upload progress changes.</param>
        public bool UploadFile(string localFilePath, string pathOnServer, ProgressAction progressAction = null)
        {
            try
            {
                var file    = new FileInfo(localFilePath);
                var address = new Uri(GetUrl(pathOnServer));
                var request = WebRequest.Create(address) as FtpWebRequest;

                request.Credentials = new NetworkCredential(networkCredential.UserName, networkCredential.Password);
                // Set control connection to closed after command execution
                request.KeepAlive = false;
                request.Method    = WebRequestMethods.Ftp.UploadFile;
                // Specify data transfer type
                request.UseBinary = true;

                // Notify server about size of uploaded file
                request.ContentLength = file.Length;
                // Set buffer size to 2KB.
                var bufferLength  = BUFFER_SIZE;
                var buffer        = new byte[bufferLength];
                var contentLength = 0;

                // Open file stream to read file
                var fs = file.OpenRead();

                // Stream to which file to be uploaded is written.
                var stream = request.GetRequestStream();
                // Read from file stream 2KB at a time.
                contentLength = fs.Read(buffer, 0, bufferLength);
                // Loop until stream content ends.
                while (contentLength != 0)
                {
                    if (progressAction != null)
                    {
                        progressAction.Invoke(fs.Position / (float)fs.Length);
                    }
                    // Write content from file stream to FTP upload stream.
                    stream.Write(buffer, 0, contentLength);
                    contentLength = fs.Read(buffer, 0, bufferLength);
                }

                // Close file and request streams
                stream.Close();
                fs.Close();
            }
            catch (Exception exc)
            {
                Debug.LogError("Error uploading file: Read ERRORS-file.\n" + exc);
                return(false);
            }
            return(true);
        }
Ejemplo n.º 8
0
    /// <summary>
    /// Initiate this progress bar's behavior on server side. Assumes position is already set to where the progress
    /// bar should appear.
    /// </summary>
    /// <param name="progressAction">progress action being performed</param>
    /// <param name="timeForCompletion">how long in seconds the action should take</param>
    /// <param name="progressEndAction">callback for when action completes or is interrupted</param>
    /// <param name="player">player performing the action</param>
    public void ServerStartProgress(ProgressAction progressAction, float timeForCompletion,
                                    IProgressEndAction progressEndAction, GameObject player)
    {
        done = true;
        playerDirectional    = player.GetComponent <Directional>();
        progress             = 0f;
        lastSpriteIndex      = 0;
        timeToFinish         = timeForCompletion;
        completedEndAction   = progressEndAction;
        facingDirectionCache = playerDirectional.CurrentDirection;
        registerPlayer       = player.GetComponent <RegisterPlayer>();
        playerSync           = player.GetComponent <PlayerSync>();
        this.progressAction  = progressAction;
        id = GetInstanceID();

        //check if something is in hand so we can interrupt if it's dropped
        var usedItemObj = player.Player().Script.playerNetworkActions.GetActiveHandItem();

        if (usedItemObj != null)
        {
            usedItem = usedItemObj.GetComponent <Pickupable>();
            if (usedItem != null)
            {
                usedItem.OnDropServer.AddListener(ServerInterruptOnDrop);
            }
        }

        if (player != PlayerManager.LocalPlayer)
        {
            //server should not see clients progress bar
            spriteRenderer.enabled = false;
        }
        else
        {
            spriteRenderer.enabled = true;
        }
        spriteRenderer.sprite = progressSprites[0];

        CommonStartProgress();

        //Start the progress for the player:
        //note: using transform position for the offset, because progress bar has no register tile and
        //otherwise it would give an incorrect offset if player is on moving matrix
        ProgressBarMessage.SendCreate(player, 0, (transform.position - player.transform.position).To2Int(), id);
    }
Ejemplo n.º 9
0
        /// <summary>
        /// Downloads a file using FTP.
        /// </summary>
        /// <param name="localFilePath">The local path to which the file which will be downloaded.</param>
        /// <param name="pathOnServer">The path on the server to download the file from.</param>
        /// <param name="progressAction">Is called when the download progress changes.</param>
        public bool DowloadFile(string localFilePath, string pathOnServer, ProgressAction progressAction = null)
        {
            try
            {
                string            url         = GetUrl(pathOnServer);
                NetworkCredential credentials = new NetworkCredential(networkCredential.UserName, networkCredential.Password);

                // Query size of the file to be downloaded
                WebRequest sizeRequest = WebRequest.Create(url);
                sizeRequest.Credentials = credentials;
                sizeRequest.Method      = WebRequestMethods.Ftp.GetFileSize;
                int fileSize = (int)sizeRequest.GetResponse().ContentLength;

                // Download the file
                WebRequest request = WebRequest.Create(url);
                request.Credentials = credentials;
                request.Method      = WebRequestMethods.Ftp.DownloadFile;

                byte[] buffer = new byte[BUFFER_SIZE];
                int    readLength;

                using (Stream ftpStream = request.GetResponse().GetResponseStream())
                {
                    using (Stream fileStream = File.Create(localFilePath))
                    {
                        while ((readLength = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            fileStream.Write(buffer, 0, readLength);
                            if (progressAction != null)
                            {
                                progressAction.Invoke((int)fileStream.Position / (float)fileSize);
                            }
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                Debug.LogError("Error downloading file: Read ERRORS-file.\n" + exc);
                return(false);
            }
            return(true);
        }
Ejemplo n.º 10
0
	private bool ExportProgressCallback(object o, ProgressAction action)
	{
		if (action == ProgressAction.Hide) {
			ProgressHBox.Visible = false;
			return false;
		}
		else if (action == ProgressAction.Show) {
			ProgressHBox.Visible = true;
			return false;
		}


		if ((double)o > 1.0)
			o = 1.0;

		ExportProgressBar.Fraction = (double)o;

		return cancelClicked;
	}
Ejemplo n.º 11
0
        public static void ExecuteProgressAction(ProgressAction action, out bool wasCancelled)
        {
            wasCancelled = false;
            ProgressWindow w = new ProgressWindow();

            action.Progress     += new System.EventHandler <urakawa.events.progress.ProgressEventArgs>(w.action_progress);
            action.Finished     += new System.EventHandler <urakawa.events.progress.FinishedEventArgs>(w.action_finished);
            action.Cancelled    += new System.EventHandler <urakawa.events.progress.CancelledEventArgs>(w.action_cancelled);
            w.mActionDescription = action.ShortDescription;
            w.Title = w.mActionDescription;
            Thread executeThread = new Thread(ExecuteWorker);

            executeThread.Start(action);
            bool?result = w.ShowDialog();

            if (result.HasValue)
            {
                wasCancelled = !result.Value;
            }
        }
Ejemplo n.º 12
0
        public bool Update(object o, ProgressAction action)
        {
            if (action == ProgressAction.Hide)
            {
                this.Visible = false;
                return(false);
            }
            else if (action == ProgressAction.Show)
            {
                this.Visible = true;
                return(false);
            }
            else if (action == ProgressAction.Message)
            {
                this.Title          = (string)o;
                MessageLabel.Markup = "<span weight=\"bold\" size=\"larger\">" + (string)o + "</span>";
                return(false);
            }
            else if (action == ProgressAction.Details)
            {
                DetailsLabel.Text = (string)o;
                return(false);
            }
            else if (action == ProgressAction.Destroy)
            {
                this.Destroy();
                return(false);
            }

            ProgressBar.Fraction = (double)o;

            if (cancelClicked == true)
            {
                cancelClicked = false;
                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 13
0
    /// <summary>
    /// Initiate this progress bar's behavior on server side. Assumes position is already set to where the progress
    /// bar should appear.
    /// </summary>
    /// <param name="progressAction">progress action being performed</param>
    /// <param name="timeForCompletion">how long in seconds the action should take</param>
    /// <param name="progressEndAction">callback for when action completes or is interrupted</param>
    /// <param name="player">player performing the action</param>
    public void ServerStartProgress(ProgressAction progressAction, float timeForCompletion,
                                    IProgressEndAction progressEndAction, GameObject player)
    {
        done = true;
        playerDirectional    = player.GetComponent <Directional>();
        progress             = 0f;
        lastSpriteIndex      = 0;
        timeToFinish         = timeForCompletion;
        completedEndAction   = progressEndAction;
        facingDirectionCache = playerDirectional.CurrentDirection;
        registerPlayer       = player.GetComponent <RegisterPlayer>();
        playerSync           = player.GetComponent <PlayerSync>();
        this.progressAction  = progressAction;
        id = GetInstanceID();

        //interrupt if hand contents are changed
        var activeSlot = player.Player().Script.ItemStorage.GetActiveHandSlot();

        activeSlot.OnSlotContentsChangeServer.AddListener(ServerInterruptOnInvChange);
        this.usedSlot = activeSlot;


        if (player != PlayerManager.LocalPlayer)
        {
            //server should not see clients progress bar
            spriteRenderer.enabled = false;
        }
        else
        {
            spriteRenderer.enabled = true;
        }
        spriteRenderer.sprite = progressSprites[0];

        CommonStartProgress();

        //Start the progress for the player:
        //note: using transform position for the offset, because progress bar has no register tile and
        //otherwise it would give an incorrect offset if player is on moving matrix
        ProgressBarMessage.SendCreate(player, 0, (transform.position - player.transform.position).To2Int(), id);
    }
Ejemplo n.º 14
0
        public static void ExecuteProgressAction(ProgressAction action, out bool wasCancelled)
        {
            wasCancelled = false;
            Progress w = new Progress();

            action.Progress     += new System.EventHandler <urakawa.events.progress.ProgressEventArgs>(w.action_progress);
            action.Finished     += new System.EventHandler <urakawa.events.progress.FinishedEventArgs>(w.action_finished);
            action.Cancelled    += new System.EventHandler <urakawa.events.progress.CancelledEventArgs>(w.action_cancelled);
            w.mActionDescription = action.ShortDescription;
            w.Text = w.mActionDescription;
            Thread executeThread = new Thread(ExecuteWorker);

            executeThread.Start(action);
            DialogResult result = w.ShowDialog();

            if (result == DialogResult.Cancel || result == DialogResult.Abort)
            {
                wasCancelled = true;
            }
            else
            {
                wasCancelled = false;
            }
        }
Ejemplo n.º 15
0
 void OnChanged(ProgressAction pa)
 {
     Changed?.Invoke(this, new ProgressArgs(pa));
 }
Ejemplo n.º 16
0
 /// <summary>
 ///     Send out progress indicator
 /// </summary>
 internal void SendProgress(int percentage, string description)
 {
     ProgressAction?.BeginInvoke(percentage, description, null, null);
     //ProgressAction?.Invoke(percentage, description);
 }
        private async void _view_FxButtonClick(object sender, EventArgs e)
        {
            _view.Status = "Будується числовий ряд функції. Будь ласка, зачекайте...";
            var   expression = "";
            var   nativeFx   = _view.Fx;
            int   start      = Convert.ToInt32(_view.RowStart);
            int   n          = Convert.ToInt32(_view.RowEnd);
            float step       = (float)Convert.ToDouble(_view.RowStep);

            float[] rowtable = new float[(int)(Math.Round(((n - start) / step)))];
            string  Row      = "";

            _view.StatusProgress.Visible = true;

            Func <bool> func = () => {
                try
                {
                    int move      = 0;
                    int invokeVal = n / 10;
                    for (float i = start; i < n; i += step)                              // 0 + step
                    {
                        expression     = nativeFx;
                        expression     = expression.Replace("x", Convert.ToString(i).Replace(',', '.'));
                        Row           += Math.Round(Convert.ToDouble(new Expression(expression).Evaluate()), 4);
                        rowtable[move] = (float)(Math.Round(Convert.ToDouble(new Expression(expression).Evaluate()), 4));
                        if (move % invokeVal == 0)
                        {
                            ProgressAction?.Invoke(10, move / invokeVal);
                        }
                        move++;
                        if (i < n - step)
                        {
                            Row += "\r\n";
                        }
                    }
                    if (move < n)
                    {
                        ProgressAction?.Invoke(n, n);
                    }
                    return(true);
                }
                catch (Exception exception)
                {
                    _message.ShowExclamation(exception.Message);
                    return(false);
                }
            };

            bool task = await Task <bool> .Factory.StartNew(func);

            string message = task ? "Готово!" : "Невдача!";

            _view.StatusProgress.Visible = false;
            _view.Status  = message;
            _view.TextRow = Row;
            _view.SetRowGrid(rowtable);
            RowGridDataChanged?.Invoke(this, EventArgs.Empty);

            _view.StartBtnEnable = task;
            rowtable             = null;
            GC.Collect();
        }
Ejemplo n.º 18
0
 public ProgressArgs(ProgressAction a)
 {
     Action = a;
 }
Ejemplo n.º 19
0
 public TextDownloader(ProgressAction progressAction)
 {
     this.progressAction = progressAction;
 }
Ejemplo n.º 20
0
 protected void UpdateProgress(ProgressAction action, int progress)
 {
     CurrentProgressAction = action;
     CurrentProgress       = progress;
     UpdateInstallStatus();
 }
Ejemplo n.º 21
0
 /// <summary>
 ///		Lanza un evento de progreso de una acción
 /// </summary>
 protected void RaiseEventProgressAction(string id, string action, string process, long actual, long total)
 {
     ProgressAction?.Invoke(this, new EventArguments.ProgressActionEventArgs(id, Source, action, process, actual, total));
 }
        private async void _view_OpenClick(object sender, EventArgs e)
        {
            _view.Status = "Завантажується проект. Будь ласка, зачекайте...";

            Image diagramRasterized = new Bitmap(_view.DiagramBox.Width, _view.DiagramBox.Height);
            Image diagramDistance   = new Bitmap(_view.DistanceBox.Width, _view.DistanceBox.Height);
            Image scaleDistance     = new Bitmap(_view.DistanceScaleBox.Width, _view.DistanceScaleBox.Height);

            _view.PointDiagram.Series[0].Points.Clear();
            _view.SplineDiagram.Series[0].Points.Clear();
            Chart pointDiagram = _view.PointDiagram.Copy();
            Chart lineDiagram  = _view.SplineDiagram.Copy();

            OpenFileDialog dialog = new OpenFileDialog();

            dialog.Filter           = "txt files (*.txt)|*.txt|wav files (*.wav)|*.wav|Recurrent plot projects (*.rpp)|*.rpp";
            dialog.FilterIndex      = 3;
            dialog.RestoreDirectory = true;

            string  path           = "";
            string  AnalysisResult = "";
            Project loaded         = new Project();

            float epsilon = 1;

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                if (dialog.OpenFile() != null)
                {
                    try
                    {
                        path = dialog.FileName;
                    }
                    catch (Exception exception)
                    {
                        _message.ShowMessage(exception.Message);
                    }
                }
            }

            _view.StatusProgress.Visible = true;

            Func <bool> func = () =>
            {
                try
                {
                    if (dialog.FilterIndex == 2)
                    {                                                           //Sound
                        loaded.Epsilon = 0.1F;
                        loaded.Row     = Audio.prepare(path);
                        char[] charArray = path.ToCharArray();
                        loaded.Name = String.Concat(charArray.Reverse().Skip(4).TakeWhile((p) => p != '\\').Reverse());
                        charArray   = null;
                    }
                    else if (dialog.FilterIndex == 1)
                    {
                        char         spliter = ' ';
                        StreamReader reader  = new StreamReader(path);
                        string       Row     = reader.ReadToEnd();

                        for (int i = 0; i < Row.Length; i++)
                        {
                            if (!(Char.IsDigit(Row[i])) && Row[i] != ',' && Row[i] != '-')
                            {
                                if (Row[i - 1] != ' ')
                                {
                                    Row = Row.Replace(Row[i], ' ');
                                }
                                else
                                {
                                    Row = Row.Remove(i, 1); i--;
                                }
                            }
                            ProgressAction?.Invoke(Row.Length, i);
                        }
                        if (!(Char.IsDigit(Row[Row.Length - 1])))
                        {
                            Row = Row.Remove(Row.Length - 1, 1);
                        }

                        float[] array = Row.Split(spliter).Select((x) => (float)(Convert.ToDouble(x))).ToArray();
                        loaded.Epsilon = 1;
                        loaded.Row     = array;
                        char[] charArray = path.ToCharArray();
                        loaded.Name = String.Concat(charArray.Reverse().Skip(4).TakeWhile((p) => p != '\\').Reverse());
                    }                       //Numbers
                    else
                    {                       //Project
                        StreamReader reader = new StreamReader(path, Encoding.Unicode);
                        string       json   = reader.ReadToEnd();
                        loaded = JsonConvert.DeserializeObject <Project>(json);
                        reader.Close();

                        ManageDiagrams(new TimeRow(loaded.Row), loaded.Epsilon, ref diagramRasterized,
                                       ref diagramDistance, ref scaleDistance, ref pointDiagram, ref lineDiagram, ref AnalysisResult);
                    }
                    return(true);
                }
                catch (Exception exception)
                {
                    _message.ShowMessage(exception.Message);
                    return(false);
                }
            };

            bool task = await Task <bool> .Factory.StartNew(func);

            string message = task ? "Готово!" : "Невдача!";

            _view.StatusProgress.Visible = false;
            _view.Status = message;

            _view.PointDiagram.Series[0]  = pointDiagram.Series[0];
            _view.SplineDiagram.Series[0] = lineDiagram.Series[0];
            _view.DiagramBox.Image        = diagramRasterized;
            _view.DistanceBox.Image       = diagramDistance;
            _view.DistanceScaleBox.Image  = scaleDistance;
            _view.Analysis = AnalysisResult;

            _view.E = epsilon.ToString();
            _view.SetRowGrid(loaded.Row);

            RowGridDataChanged?.Invoke(this, EventArgs.Empty);
            _view.StartBtnEnable = task;

            /*** project reload ***/
            project        = loaded;
            _view.FormName = project.Name + appName;

            loaded            = null;
            AnalysisResult    = null;
            diagramRasterized = null;
            diagramDistance   = null;
            scaleDistance     = null;
            pointDiagram      = null;
            lineDiagram       = null;

            GC.Collect();
        }
Ejemplo n.º 23
0
 public ProgressArgs(ProgressAction a)
 {
     Action = a;
 }
        private async void _view_RandomRowClick(object sender, EventArgs e)
        {
            _view.Status = "Генерується ряд випадкових чисел. Будь ласка, зачекайте...";

            string  N        = _view.N;
            string  Row      = "";
            TimeRow rowtable = new TimeRow();

            _view.StatusProgress.Visible = true;
            Func <bool> func = () =>
            {
                try
                {
                    TimeRow row       = new TimeRow(Convert.ToInt32(N), 100);
                    int     max       = row.GetSize();
                    int     move      = 0;
                    int     invokeVal = max / 10;
                    rowtable = row;
                    for (int i = 0; i < row.GetSize(); i++)
                    {
                        Row += Math.Round(row[i], 4);
                        if (i < row.GetSize() - 1)
                        {
                            Row += '\r';
                            Row += '\n';
                        }
                        move++;
                        if (move % invokeVal == 0)
                        {
                            ProgressAction?.Invoke(10, move / invokeVal);
                        }
                    }

                    row.Dispose();
                    return(true);
                }
                catch (Exception exception)
                {
                    //_message.ShowError("Невірно задані параметри.");
                    _message.ShowError(exception.Message);
                    return(false);
                }
            };

            bool task = await Task <bool> .Factory.StartNew(func);

            string message = task ? "Готово!" : "Невдача!";

            _view.StatusProgress.Visible = false;

            _view.Status  = message;
            _view.TextRow = Row;
            _view.SetRowGrid(rowtable.Row);

            RowGridDataChanged?.Invoke(this, EventArgs.Empty);
            _view.StartBtnEnable = task;

            Row = null;
            rowtable.Dispose();
            GC.Collect();
        }
Ejemplo n.º 25
0
        /// <summary>
        /// 指定されたパスの画像を連結し、Gifを生成する処理を開始する
        /// </summary>
        /// <param name="imageFilePaths">
        /// 画像ファイルのパス配列
        /// (配列の順番で連結する、
        ///  指定されたパスのファイルが画像ファイルでない場合、そのファイルは無視する)
        /// </param>
        /// <param name="frameRate">
        /// 生成するGifのフレームレート
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// 引数の画像ファイルのパス配列(<paramref name="imageFilePaths"/>)がNULLの場合に発生
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        /// 引数のフレームレート(<paramref name="frameRate"/>)が 0以下の値の場合に発生
        /// </exception>
        /// <exception cref="ArgumentException">
        /// 変換処理で生成したGifファイルの保存先パス(<see cref="SavePath"/>)に
        /// <see cref="Path.GetInvalidPathChars"/> で定義される無効な文字が含まれている場合に発生
        /// </exception>
        /// <exception cref="NotSupportedException">
        /// 変換処理で生成したGifファイルの保存先パス(<see cref="SavePath"/>)に
        /// ドライブラベル(C:\)の一部ではないコロン文字(:)が含まれている場合
        /// </exception>
        /// <exception cref="IOException">
        /// 変換処理で生成したGifファイルの保存先パス(<see cref="SavePath"/>)が以下の場合に発生する
        /// ・保存先パスがシステム定義の最大長を超えている場合
        ///  (Windowsでは、パスは 248 文字未満、ファイル名は 260 文字未満にする必要がある)
        ///  [<see cref="PathTooLongException"/>]
        /// ・保存先パスが示すディレクトリが正しくない場合
        ///  (マップされていないドライブ名が指定されている場合等)
        ///  [<see cref="DirectoryNotFoundException"/>]
        /// ・I/O エラーが発生した場合
        ///  [<see cref="IOException"/>]
        /// </exception>
        /// <exception cref="UnauthorizedAccessException">
        /// 変換処理で生成したGifファイルの保存先パス(<see cref="SavePath"/>)において、
        /// 隠しファイル等のアクセスできないファイルが既に存在している場合に発生
        /// </exception>
        /// <exception cref="System.Security.SecurityException">
        /// 呼び出し元に、必要なアクセス許可がない場合に発生
        /// </exception>
        /// <exception cref="GifEncoderException">
        /// Gifデータへのエンコードに失敗した場合に発生
        /// </exception>
        /// <returns>処理が正常終了した場合 True、中断した場合 False</returns>
        public bool StartCombineImages(string[] imageFilePaths, decimal frameRate)
        {
            // 引数チェック
            if (imageFilePaths == null)
            {
                throw new ArgumentNullException(nameof(imageFilePaths));
            }
            else if (frameRate < 0)
            {
                throw new ArgumentOutOfRangeException(
                          paramName: nameof(frameRate),
                          actualValue: frameRate,
                          message: string.Format(
                              CultureInfo.InvariantCulture,
                              CommonMessage.ArgumentOutOfRangeExceptionMessageFormatOrLess,
                              0));
            }

            // 変換処理を実行する
            try
            {
                // 実行中フラグを ON にする
                IsRunningCombineImages = true;

                // Gifエンコーダー生成
                GifEncoder gifEncoder;
                using (gifEncoder = new GifEncoder(SavePath, true, 0))
                {
                    // 都度都度保存する
                    gifEncoder.IsEachTimeSave = true;

                    // 設定するディレイ用のパラメータの初期値を設定
                    int remainder = 0;
                    int delay;

                    // イメージデータを読み込みGifエンコーダに追加していく
                    int count = 1;
                    foreach (string imagePath in imageFilePaths)
                    {
                        // 実行中でない場合、処理を中断する
                        if (!IsRunningCombineImages)
                        {
                            return(false);
                        }

                        // 読み込み可能な画像データのみ追加していく
                        Image image = null;
                        try
                        {
                            if (ImageTransform.TryImageLoad(imagePath, out image))
                            {
                                // 設定するディレイを計算
                                delay     = decimal.ToInt32((GifEncoder.GifDelayUnit + remainder) / frameRate);
                                remainder = decimal.ToInt32((GifEncoder.GifDelayUnit + remainder) % frameRate);

                                // 画像データをGifに追加
                                try
                                {
                                    gifEncoder.AddImage(image, (short)delay);
                                }
                                catch (ExternalException)
                                {
                                    // 画像データ不正のエラーの場合は無視する
                                }
                            }
                        }
                        finally
                        {
                            // 読み込んだ画像リソースの解放
                            image?.Dispose();
                        }

                        // 進捗を進める
                        int progressRate = count * 100 / imageFilePaths.Length;
                        ProgressAction?.Invoke(progressRate);
                        count++;
                    }

                    // 生成したGifを保存する
                    gifEncoder.Save();
                }

                // 正常終了:True を返す
                return(true);
            }
            finally
            {
                // 実行中フラグを OFF にする
                IsRunningCombineImages = false;
            }
        }
Ejemplo n.º 26
0
 void OnChanged(ProgressAction pa)
 {
     if (Changed != null)
         Changed(this, new ProgressArgs(pa));
 }
Ejemplo n.º 27
0
 public TextDownloader(ProgressAction progressAction, AfterFinishAction afterFinishAction)
 {
     this.progressAction = progressAction;
     this.afterFinish = afterFinishAction;
     counter = 0;
 }