Exemplo n.º 1
0
 // Start is called before the first frame update
 void Start()
 {
     /* Check to see if Farm exists, and if so, don't create a new one */
     if (!existsInScene)
     {
         existsInScene = true;
         DontDestroyOnLoad(transform.gameObject);
         farm = new CropInfo[numberOfPlotsHeight, numberOfPlotsWidth];
         for (int i = 0; i < numberOfPlotsHeight; ++i)
         {
             for (int j = 0; j < numberOfPlotsWidth; ++j)
             {
                 farm[i, j]             = new CropInfo();
                 farm[i, j].watered     = false;
                 farm[i, j].growTime    = 0;
                 farm[i, j].seedType    = "";
                 farm[i, j].growthStage = 0;
             }
         }
     }
     else
     {
         Destroy(gameObject);
     }
 }
Exemplo n.º 2
0
        public ActionResult DeleteConfirmed(int id)
        {
            CropInfo cropInfo = db.CropInfoes.Find(id);

            db.CropInfoes.Remove(cropInfo);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Exemplo n.º 3
0
 public ActionResult Edit([Bind(Include = "CropID,Name,Description,Season,Spacing,AverageYield,IrrigationInterval,GrowthTime,LifeExpect,Disabled")] CropInfo cropInfo)
 {
     if (ModelState.IsValid)
     {
         db.Entry(cropInfo).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(cropInfo));
 }
Exemplo n.º 4
0
 public CropInfo GetCropInfoByName(string cropName)
 {
     try
     {
         CropInfo cropInfo = db.CropInfoes.Select(x => x).Where(x => x.CropName == cropName).FirstOrDefault();
         return(cropInfo);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Exemplo n.º 5
0
 public CropInfo GetCropInfoById(int id)
 {
     try
     {
         CropInfo cropInfo = db.CropInfoes.Select(x => x).Where(x => x.CropID == id).FirstOrDefault();
         return(cropInfo);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Exemplo n.º 6
0
        // GET: CropInfoes/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            CropInfo cropInfo = db.CropInfoes.Find(id);

            if (cropInfo == null)
            {
                return(HttpNotFound());
            }
            return(View(cropInfo));
        }
        public static void CropMove(this CropInfo cropInfo, Size imageAreaSize, double deltaX = 0, double dextaY = 0)
        {
            if (cropInfo.IsEmpty)
            {
                return;
            }
            //处理左右位置
            if (cropInfo.WidthScale > 1)
            {
                cropInfo.LeftScale = (1 - cropInfo.WidthScale) / 2;
            }
            else
            {
                cropInfo.LeftScale += deltaX / imageAreaSize.Width;
                if (cropInfo.LeftScale < 0)
                {
                    cropInfo.LeftScale = 0;
                }
                if (cropInfo.LeftScale + cropInfo.WidthScale > 1)
                {
                    cropInfo.LeftScale = 1 - cropInfo.WidthScale;
                }
            }

            //处理上下位置
            if (cropInfo.HeightScale > 1)
            {
                {
                    cropInfo.TopScale = (1 - cropInfo.HeightScale) / 2;
                }
            }
            else
            {
                cropInfo.TopScale += dextaY / imageAreaSize.Height;
                if (cropInfo.TopScale < 0)
                {
                    cropInfo.TopScale = 0;
                }
                if (cropInfo.TopScale + cropInfo.HeightScale > 1)
                {
                    cropInfo.TopScale = 1 - cropInfo.HeightScale;
                }
            }
        }
Exemplo n.º 8
0
    public void AddCrop(
        string id,

        Item item,
        string name,
        SpriteInfo?sprite,

        bool isTrellisCrop,
        bool isGiantCrop,
        SpriteInfo?giantSprite,
        Item[]?seeds,
        bool isPaddyCrop,

        IEnumerable <int> phases,
        IEnumerable <SpriteInfo?>?phaseSprites,

        int regrow,

        WorldDate start,
        WorldDate end
        )
    {
        Crops[id] = new CropInfo(
            Id: id,
            Item: item,
            Name: name,
            Sprite: sprite,
            IsTrellisCrop: isTrellisCrop,
            IsGiantCrop: isGiantCrop,
            GiantSprite: giantSprite,
            Seeds: seeds,
            Phases: phases.ToArray(),
            PhaseSprites: phaseSprites?.ToArray(),
            Regrow: regrow,
            IsPaddyCrop: isPaddyCrop,
            StartDate: start,
            EndDate: end
            );
    }
Exemplo n.º 9
0
        protected override void Seed(Sprint_3_V1.Models.Sprint_3_V1Context context)
        {
            Account admin = new Account
            {
                UserName        = "******",
                Password        = "******",
                ConfirmPassword = "******",
                Role            = "Admin",
                Disabled        = false,
                Type            = "Admin",
                AccountID       = 1,
                Customer        = null,
                Employee        = null
            };

            context.Accounts.Add(admin);
            context.SaveChanges();

            IList <Position> positions = new List <Position>();

            positions.Add(new Position()
            {
                PositionID  = 1,
                Name        = "Manager",
                Description = "Manage Farm",
                BaseSalary  = 1234.0,
                Disabled    = false,
                EmpPos      = null
            });
            positions.Add(new Position()
            {
                PositionID  = 2,
                Name        = "Human resources",
                Description = "Manage Farmers",
                BaseSalary  = 1234.0,
                Disabled    = false,
                EmpPos      = null
            });
            positions.Add(new Position()
            {
                PositionID  = 3,
                Name        = "Worker",
                Description = "Field work",
                BaseSalary  = 1230.0,
                Disabled    = false,
                EmpPos      = null
            });
            positions.Add(new Position()
            {
                PositionID  = 4,
                Name        = "Foreman",
                Description = "Manage Farmers",
                BaseSalary  = 123.0,
                Disabled    = false,
                EmpPos      = null
            });
            positions.Add(new Position()
            {
                PositionID  = 5,
                Name        = "Clerk",
                Description = "Manage Admin",
                BaseSalary  = 120.0,
                Disabled    = false,
                EmpPos      = null
            });
            positions.Add(new Position()
            {
                PositionID  = 6,
                Name        = "Delivery",
                Description = "Deliver",
                BaseSalary  = 120.0,
                Disabled    = false,
                EmpPos      = null
            });

            context.Positions.AddRange(positions);
            context.SaveChanges();


            CropInfo crop = new CropInfo
            {
                CropID             = 1,
                Name               = "Cabbage",
                Description        = "Cabbage farm",
                Season             = "Summer",
                Spacing            = 2,
                AverageYield       = 100,
                IrrigationInterval = 3,
                GrowthTime         = 60,
                LifeExpect         = 30,
                Disabled           = false
            };

            context.CropInfoes.Add(crop);
            context.SaveChanges();

            Stock stock = new Stock
            {
                StockID     = 1,
                CurQuantity = 100,
                HarQuantity = 100,
                Harvested   = DateTime.Now,
                Expiery     = DateTime.Now.AddDays(30),
                ExpFlag     = false,
                Price       = 100,
                Disabled    = false,
                CropID      = 1
            };

            context.Stocks.Add(stock);
            context.SaveChanges();

            //StocksImage stocksimage = new StocksImage
            //{
            //    StockImageID = 1,
            //    StockID = 1,
            //    ImageName = "Cabbage",
            //    StockImage = ImageToArray(),

            //};
            //context.StocksImages.Add(stocksimage);
            //context.SaveChanges();

            base.Seed(context);

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data.
        }
Exemplo n.º 10
0
        public void ConvertVideo(Action <string> log, Action <string> setStatus, Action <double> setProgress,
                                 Action <bool> setIsIndeterminate, string sourceFile, string outputFile, CropInfo cropInfo)
        {
            setStatus("Converting Video");
            setIsIndeterminate(true);

            CheckOutputDirectory(log, Path.GetDirectoryName(outputFile));

            log(Environment.NewLine + Environment.NewLine + "Executing '" + FFMPEGExe + "' on '" + sourceFile + "'...");

            ProcessStartInfo psi = new ProcessStartInfo(FFMPEGExe)
            {
                Arguments              = "-y" + (cropInfo.CropStart ? " -ss " + cropInfo.Start.ToString(CultureInfo.InvariantCulture) : null) + " -i \"" + sourceFile + "\" -analyzeduration " + int.MaxValue + " -probesize " + int.MaxValue + " -c:v copy" + (cropInfo.CropEnd ? " -t " + cropInfo.Length.ToString(CultureInfo.InvariantCulture) : null) + " \"" + outputFile + "\"",
                RedirectStandardError  = true,
                RedirectStandardOutput = true,
                StandardErrorEncoding  = Encoding.UTF8,
                StandardOutputEncoding = Encoding.UTF8,
                UseShellExecute        = false,
                CreateNoWindow         = true
            };

            log(Environment.NewLine + "Command line arguments: " + psi.Arguments + Environment.NewLine);

            using (Process p = new Process())
            {
                FixedSizeQueue <string> logQueue = new FixedSizeQueue <string>(200);

                TimeSpan duration = TimeSpan.FromSeconds(cropInfo.Length);

                DataReceivedEventHandler outputDataReceived = new DataReceivedEventHandler((s, e) =>
                {
                    try
                    {
                        if (!string.IsNullOrWhiteSpace(e.Data))
                        {
                            string dataTrimmed = e.Data.Trim();

                            logQueue.Enqueue(dataTrimmed);

                            if (dataTrimmed.StartsWith("frame", StringComparison.OrdinalIgnoreCase) && duration != TimeSpan.Zero)
                            {
                                string timeStr = dataTrimmed.Substring(dataTrimmed.IndexOf("time") + 4).Trim();
                                timeStr        = timeStr.Substring(timeStr.IndexOf("=") + 1).Trim();
                                timeStr        = timeStr.Substring(0, timeStr.IndexOf(" ")).Trim();

                                if (TimeSpan.TryParse(timeStr, out TimeSpan current))
                                {
                                    setIsIndeterminate(false);
                                    setProgress(current.TotalMilliseconds / duration.TotalMilliseconds * 100);
                                }
                                else
                                {
                                    setIsIndeterminate(true);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        log(Environment.NewLine + "An error occured while reading '" + FFMPEGExe + "' output stream!" + Environment.NewLine + Environment.NewLine + ex.ToString());
                    }
                });

                p.OutputDataReceived += outputDataReceived;
                p.ErrorDataReceived  += outputDataReceived;
                p.StartInfo           = psi;
                p.Start();
                p.BeginErrorReadLine();
                p.BeginOutputReadLine();
                p.WaitForExit();

                if (p.ExitCode == 0)
                {
                    log(Environment.NewLine + "Video conversion complete!");
                }
                else
                {
                    if (!logQueue.IsEmpty)
                    {
                        foreach (string line in logQueue)
                        {
                            log(Environment.NewLine + line);
                        }
                    }

                    throw new ApplicationException("An error occured while converting the video!");
                }
            }
        }
Exemplo n.º 11
0
        private void StartQueuedDownloadIfExists()
        {
            if (_paused)
            {
                return;
            }

            if (Monitor.TryEnter(_changeDownloadLockObject))
            {
                try
                {
                    if (!_downloads.Where(d => d.DownloadState == DownloadState.Downloading).Any())
                    {
                        TwitchVideoDownload download = _downloads.Where(d => d.DownloadState == DownloadState.Queued).FirstOrDefault();

                        if (download == null)
                        {
                            return;
                        }

                        DownloadParameters downloadParams = download.DownloadParams;

                        CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
                        CancellationToken       cancellationToken       = cancellationTokenSource.Token;

                        string downloadId = download.Id;
                        string vodId      = downloadParams.Video.Id;
                        string tempDir    = Path.Combine(_preferencesService.CurrentPreferences.DownloadTempFolder, downloadId);
                        string ffmpegFile = _processingService.FFMPEGExe;
                        string concatFile = Path.Combine(tempDir, Path.GetFileNameWithoutExtension(downloadParams.FullPath) + ".ts");
                        string outputFile = downloadParams.FullPath;

                        bool disableConversion = downloadParams.DisableConversion;
                        bool cropStart         = downloadParams.CropStart;
                        bool cropEnd           = downloadParams.CropEnd;

                        TimeSpan cropStartTime = downloadParams.CropStartTime;
                        TimeSpan cropEndTime   = downloadParams.CropEndTime;

                        TwitchVideoQuality quality = downloadParams.SelectedQuality;

                        Action <DownloadState> setDownloadState = download.SetDownloadState;
                        Action <string>        log                = download.AppendLog;
                        Action <string>        setStatus          = download.SetStatus;
                        Action <double>        setProgress        = download.SetProgress;
                        Action <bool>          setIsIndeterminate = download.SetIsIndeterminate;

                        Task downloadVideoTask = new Task(() =>
                        {
                            setStatus("Initializing");

                            log("Download task has been started!");

                            WriteDownloadInfo(log, downloadParams, ffmpegFile, tempDir);

                            cancellationToken.ThrowIfCancellationRequested();

                            log(Environment.NewLine + Environment.NewLine + "Retrieving VOD access information...");
                            TwitchVideoAuthInfo vodAuthInfo = _apiService.GetVodAuthInfo(vodId);
                            log(" done!");

                            cancellationToken.ThrowIfCancellationRequested();

                            WriteVodAuthInfo(log, vodAuthInfo);

                            cancellationToken.ThrowIfCancellationRequested();

                            CheckTempDirectory(log, tempDir);

                            cancellationToken.ThrowIfCancellationRequested();

                            log(Environment.NewLine + Environment.NewLine + "Retrieving playlist information for all VOD qualities...");
                            Dictionary <TwitchVideoQuality, string> playlistInfo = _apiService.GetPlaylistInfo(vodId, vodAuthInfo);
                            log(" done!");

                            cancellationToken.ThrowIfCancellationRequested();

                            WritePlaylistInfo(log, playlistInfo);

                            cancellationToken.ThrowIfCancellationRequested();

                            TwitchPlaylist vodPlaylist = GetVodPlaylist(log, tempDir, playlistInfo, quality);

                            cancellationToken.ThrowIfCancellationRequested();

                            CropInfo cropInfo = CropVodPlaylist(vodPlaylist, cropStart, cropEnd, cropStartTime, cropEndTime);

                            cancellationToken.ThrowIfCancellationRequested();

                            DownloadParts(log, setStatus, setProgress, vodPlaylist, cancellationToken);

                            cancellationToken.ThrowIfCancellationRequested();

                            _processingService.ConcatParts(log, setStatus, setProgress, vodPlaylist, disableConversion ? outputFile : concatFile);

                            if (!disableConversion)
                            {
                                cancellationToken.ThrowIfCancellationRequested();
                                _processingService.ConvertVideo(log, setStatus, setProgress, setIsIndeterminate, concatFile, outputFile, cropInfo);
                            }
                        }, cancellationToken);

                        Task continueTask = downloadVideoTask.ContinueWith(task =>
                        {
                            log(Environment.NewLine + Environment.NewLine + "Starting temporary download folder cleanup!");
                            CleanUp(tempDir, log);

                            setProgress(100);
                            setIsIndeterminate(false);

                            bool success = false;

                            if (task.IsFaulted)
                            {
                                setDownloadState(DownloadState.Error);
                                log(Environment.NewLine + Environment.NewLine + "Download task ended with an error!");

                                if (task.Exception != null)
                                {
                                    log(Environment.NewLine + Environment.NewLine + task.Exception.ToString());
                                }
                            }
                            else if (task.IsCanceled)
                            {
                                setDownloadState(DownloadState.Canceled);
                                log(Environment.NewLine + Environment.NewLine + "Download task was canceled!");
                            }
                            else
                            {
                                success = true;
                                setDownloadState(DownloadState.Done);
                                log(Environment.NewLine + Environment.NewLine + "Download task ended successfully!");
                            }

                            if (!_downloadTasks.TryRemove(downloadId, out DownloadTask downloadTask))
                            {
                                throw new ApplicationException("Could not remove download task with ID '" + downloadId + "' from download task collection!");
                            }

                            if (success && _preferencesService.CurrentPreferences.DownloadRemoveCompleted)
                            {
                                _eventAggregator.GetEvent <RemoveDownloadEvent>().Publish(downloadId);
                            }
                        });

                        if (_downloadTasks.TryAdd(downloadId, new DownloadTask(downloadVideoTask, continueTask, cancellationTokenSource)))
                        {
                            downloadVideoTask.Start();
                            setDownloadState(DownloadState.Downloading);
                        }
                    }
                }
                finally
                {
                    Monitor.Exit(_changeDownloadLockObject);
                }
            }
        }
Exemplo n.º 12
0
        private void EncodeVideo(Action <string> log, Action <string> setStatus, Action <int> setProgress,
                                 Action <bool> setIsEncoding, string ffmpegFile, string playlistFile, string outputFile, CropInfo cropInfo)
        {
            setStatus("Encoding");
            setIsEncoding(true);

            log(Environment.NewLine + Environment.NewLine + "Executing '" + ffmpegFile + "' on local playlist...");

            ProcessStartInfo psi = new ProcessStartInfo(ffmpegFile);

            psi.Arguments              = "-y" + (cropInfo.CropStart ? " -ss " + cropInfo.Start.ToString(CultureInfo.InvariantCulture) : null) + " -i \"" + playlistFile + "\" -c:v copy -c:a copy -bsf:a aac_adtstoasc" + (cropInfo.CropEnd ? " -t " + cropInfo.Length.ToString(CultureInfo.InvariantCulture) : null) + " \"" + outputFile + "\"";
            psi.RedirectStandardError  = true;
            psi.RedirectStandardOutput = true;
            psi.StandardErrorEncoding  = Encoding.UTF8;
            psi.StandardOutputEncoding = Encoding.UTF8;
            psi.UseShellExecute        = false;
            psi.CreateNoWindow         = true;

            log(Environment.NewLine + "Command line arguments: " + psi.Arguments + Environment.NewLine);

            using (Process p = new Process())
            {
                TimeSpan duration = new TimeSpan();

                bool durationReceived = false;

                DataReceivedEventHandler outputDataReceived = new DataReceivedEventHandler((s, e) =>
                {
                    try
                    {
                        if (!string.IsNullOrWhiteSpace(e.Data))
                        {
                            string dataTrimmed = e.Data.Trim();

                            if (dataTrimmed.StartsWith("Duration") && !durationReceived)
                            {
                                string durationStr = dataTrimmed.Substring(dataTrimmed.IndexOf(":") + 1).Trim();
                                durationStr        = durationStr.Substring(0, durationStr.IndexOf(",")).Trim();

                                if (TimeSpan.TryParse(durationStr, out duration))
                                {
                                    duration         = TimeSpan.Parse(durationStr);
                                    durationReceived = true;
                                    setProgress(0);
                                }
                            }

                            if (dataTrimmed.StartsWith("frame") && durationReceived && duration != TimeSpan.Zero)
                            {
                                string timeStr = dataTrimmed.Substring(dataTrimmed.IndexOf("time") + 4).Trim();
                                timeStr        = timeStr.Substring(timeStr.IndexOf("=") + 1).Trim();
                                timeStr        = timeStr.Substring(0, timeStr.IndexOf(" ")).Trim();

                                TimeSpan current;

                                if (TimeSpan.TryParse(timeStr, out current))
                                {
                                    setIsEncoding(false);
                                    setProgress((int)(current.TotalMilliseconds * 100 / duration.TotalMilliseconds));
                                }
                                else
                                {
                                    setIsEncoding(true);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        log(Environment.NewLine + "An error occured while reading '" + ffmpegFile + "' output stream!" + Environment.NewLine + Environment.NewLine + ex.ToString());
                    }
                });

                p.OutputDataReceived += outputDataReceived;
                p.ErrorDataReceived  += outputDataReceived;
                p.StartInfo           = psi;
                p.Start();
                p.BeginErrorReadLine();
                p.BeginOutputReadLine();
                p.WaitForExit();

                if (p.ExitCode == 0)
                {
                    log(Environment.NewLine + "Encoding complete!");
                }
                else
                {
                    throw new ApplicationException("An error occured while encoding the video!");
                }
            }
        }
Exemplo n.º 13
0
        private void StartQueuedDownloadIfExists()
        {
            if (this.paused)
            {
                return;
            }

            if (Monitor.TryEnter(this.changeDownloadLockObject))
            {
                try
                {
                    if (!this.downloads.Where(d => d.DownloadStatus == DownloadStatus.Active).Any())
                    {
                        TwitchVideoDownload download = this.downloads.Where(d => d.DownloadStatus == DownloadStatus.Queued).FirstOrDefault();

                        if (download == null)
                        {
                            return;
                        }

                        DownloadParameters downloadParams = download.DownloadParams;

                        CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
                        CancellationToken       cancellationToken       = cancellationTokenSource.Token;

                        string downloadId   = download.Id;
                        string urlIdTrimmed = downloadParams.Video.IdTrimmed;
                        string tempDir      = Path.Combine(downloadParams.Folder, TEMP_PREFIX + downloadId);
                        string playlistFile = Path.Combine(tempDir, PLAYLIST_NAME);
                        string ffmpegFile   = Path.Combine(appDir, Environment.Is64BitOperatingSystem ? FFMPEG_EXE_X64 : FFMPEG_EXE_X86);
                        string outputFile   = downloadParams.FullPath;

                        bool cropStart = downloadParams.CropStart;
                        bool cropEnd   = downloadParams.CropEnd;

                        TimeSpan cropStartTime = downloadParams.CropStartTime;
                        TimeSpan cropEndTime   = downloadParams.CropEndTime;

                        TwitchVideoResolution resolution = downloadParams.Resolution;

                        Action <DownloadStatus> setDownloadStatus = download.SetDownloadStatus;
                        Action <string>         log           = download.AppendLog;
                        Action <string>         setStatus     = download.SetStatus;
                        Action <int>            setProgress   = download.SetProgress;
                        Action <bool>           setIsEncoding = download.SetIsEncoding;

                        Task downloadVideoTask = new Task(() =>
                        {
                            setStatus("Initializing");

                            log("Download task has been started!");

                            this.WriteDownloadInfo(log, downloadParams, ffmpegFile, tempDir);

                            this.CheckTempDirectory(log, tempDir);

                            using (WebClient webClient = new WebClient())
                            {
                                AuthInfo authInfo = this.RetrieveAuthInfo(log, webClient, urlIdTrimmed);

                                cancellationToken.ThrowIfCancellationRequested();

                                string playlistUrl = this.RetrievePlaylistUrlForQuality(log, webClient, resolution, urlIdTrimmed, authInfo);

                                cancellationToken.ThrowIfCancellationRequested();

                                WebChunkList webChunkList = this.RetrieveWebChunkList(log, webClient, tempDir, playlistUrl);

                                cancellationToken.ThrowIfCancellationRequested();

                                CropInfo cropInfo = this.CropWebChunkList(webChunkList, cropStart, cropEnd, cropStartTime, cropEndTime);

                                cancellationToken.ThrowIfCancellationRequested();

                                this.DownloadChunks(log, setStatus, setProgress, webChunkList, cancellationToken);

                                cancellationToken.ThrowIfCancellationRequested();

                                this.WriteNewPlaylist(log, webChunkList, playlistFile);

                                cancellationToken.ThrowIfCancellationRequested();

                                this.EncodeVideo(log, setStatus, setProgress, setIsEncoding, ffmpegFile, playlistFile, outputFile, cropInfo);
                            }
                        }, cancellationToken);

                        Task continueTask = downloadVideoTask.ContinueWith(task =>
                        {
                            log(Environment.NewLine + Environment.NewLine + "Starting temporary download folder cleanup!");
                            this.CleanUp(tempDir, log);

                            setProgress(100);
                            setIsEncoding(false);

                            bool success = false;

                            if (task.IsFaulted)
                            {
                                setDownloadStatus(DownloadStatus.Error);
                                log(Environment.NewLine + Environment.NewLine + "Download task ended with an error!");

                                if (task.Exception != null)
                                {
                                    log(Environment.NewLine + Environment.NewLine + task.Exception.ToString());
                                }
                            }
                            else if (task.IsCanceled)
                            {
                                setDownloadStatus(DownloadStatus.Canceled);
                                log(Environment.NewLine + Environment.NewLine + "Download task was canceled!");
                            }
                            else
                            {
                                success = true;
                                setDownloadStatus(DownloadStatus.Finished);
                                log(Environment.NewLine + Environment.NewLine + "Download task ended successfully!");
                            }

                            DownloadTask downloadTask;

                            if (!this.downloadTasks.TryRemove(downloadId, out downloadTask))
                            {
                                throw new ApplicationException("Could not remove download task with ID '" + downloadId + "' from download task collection!");
                            }

                            if (success && this.preferencesService.CurrentPreferences.DownloadRemoveCompleted)
                            {
                                this.eventAggregator.GetEvent <DownloadCompletedEvent>().Publish(downloadId);
                            }
                        });

                        if (this.downloadTasks.TryAdd(downloadId, new DownloadTask(downloadVideoTask, continueTask, cancellationTokenSource)))
                        {
                            downloadVideoTask.Start();
                            setDownloadStatus(DownloadStatus.Active);
                        }
                    }
                }
                finally
                {
                    Monitor.Exit(this.changeDownloadLockObject);
                }
            }
        }