Пример #1
0
        private void EndUpdateAsync(DeploymentManager dm, Exception error, bool cancelled)
        {
            Interlocked.Exchange(ref this._guard, 0);
            AsyncCompletedEventArgs    e = new AsyncCompletedEventArgs(error, cancelled, (object)null);
            AsyncCompletedEventHandler completedEventHandler = (AsyncCompletedEventHandler)this.Events[ApplicationDeployment.updateCompletedKey];

            if (completedEventHandler != null)
            {
                completedEventHandler((object)this, e);
            }
            if (dm == null)
            {
                return;
            }
            dm.ProgressChanged      -= new DeploymentProgressChangedEventHandler(this.UpdateProgressChangedEventHandler);
            dm.BindCompleted        -= new BindCompletedEventHandler(this.UpdateBindCompletedEventHandler);
            dm.SynchronizeCompleted -= new SynchronizeCompletedEventHandler(this.SynchronizeNullCompletedEventHandler);
            new NamedPermissionSet("FullTrust").Assert();
            try
            {
                dm.Dispose();
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }
        }
Пример #2
0
        /// <summary>Downloads the resource with the specified URI to a local file, asynchronously.</summary>
        /// <param name="webClient">The WebClient.</param>
        /// <param name="address">The URI from which to download data.</param>
        /// <param name="fileName">The name of the local file that is to receive the data.</param>
        /// <returns>A Task that contains the downloaded data.</returns>
        public static Task DownloadFileTask(this WebClient webClient, Uri address, string fileName)
        {
            // Create the task to be returned
            var tcs = new TaskCompletionSource <object>(address);

            // Setup the callback event handler
            AsyncCompletedEventHandler handler = null;

            handler = (sender, e) => EAPCommon.HandleCompletion(tcs, e, () => null, () => webClient.DownloadFileCompleted -= handler);
            webClient.DownloadFileCompleted += handler;

            // Start the async work
            try
            {
                webClient.DownloadFileAsync(address, fileName, tcs);
            }
            catch (Exception exc)
            {
                // If something goes wrong kicking off the async work,
                // unregister the callback and cancel the created task
                webClient.DownloadFileCompleted -= handler;
                tcs.TrySetException(exc);
            }

            // Return the task that represents the async operation
            return(tcs.Task);
        }
Пример #3
0
        public static void DownloadFileAsync(string fileLocation,
                                             DownloadProgressChangedEventHandler downloadHandler,
                                             AsyncCompletedEventHandler downloadCompletedHandler, string fileName)
        {
            General.IsUpdating = true;

            try
            {
                using (ByteGuardWebClient byteguardWebClient = new ByteGuardWebClient())
                {
                    byteguardWebClient.CookieJar = CookieContainer;

                    byteguardWebClient.DownloadProgressChanged += downloadHandler;
                    byteguardWebClient.DownloadFileCompleted   += downloadCompletedHandler;

                    Uri postUri =
                        new Uri(
                            String.Format("{0}process.php?act=downloadupdate&filename={1}", General.ByteGuardHost, fileName));

                    lock (LockObject)
                    {
                        byteguardWebClient.DownloadFileAsync(postUri, fileLocation);
                    }
                }
            }
            catch
            {
                MessageBox.Show("Failed to download update, please try again shortly.", "Update Error", MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
        }
Пример #4
0
        /// <inheritdoc/>
        public void AddAttachment(FileTransferInformation fileTransferInfo, AsyncCompletedEventHandler sendFileCompletedCallback, Uri uri, string friendlyName)
        {
            ValidateArg.NotNull(fileTransferInfo, nameof(fileTransferInfo));

            if (string.IsNullOrEmpty(this.SessionOutputDirectory))
            {
                if (EqtTrace.IsErrorEnabled)
                {
                    EqtTrace.Error(
                        "DataCollectionAttachmentManager.AddAttachment: Initialize not invoked.");
                }

                return;
            }

            if (!this.AttachmentSets.ContainsKey(uri))
            {
                this.AttachmentSets.Add(uri, new AttachmentSet(uri, friendlyName));
            }

            if (fileTransferInfo != null)
            {
                this.AddNewFileTransfer(fileTransferInfo, sendFileCompletedCallback, uri, friendlyName);
            }
            else
            {
                if (EqtTrace.IsErrorEnabled)
                {
                    EqtTrace.Error("DataCollectionAttachmentManager.AddAttachment: Got unexpected message of type FileTransferInformationExtension.");
                }
            }
        }
 public void Download(string dataPath, AsyncCompletedEventHandler callback)
 {
     try {
         using (WebClient client = new WebClient()) {
             FileInfo dest = new FileInfo(Path.Combine(dataPath, "Updates", this.Latest.FileName));
             if (!dest.Directory.Exists)
             {
                 dest.Directory.Create();
             }
             client.DownloadFileCompleted += delegate(object sender, AsyncCompletedEventArgs e) {
                 if (!e.Cancelled && (e.Error == null))
                 {
                     this.Unzip(dest.FullName);
                     callback(sender, e);
                 }
             };
             client.DownloadFileAsync(new Uri(this.Latest.FileUrl), dest.FullName);
         }
     }
     catch (WebException exception) {
         if (this.Error != null)
         {
             this.Error(this, new UnhandledExceptionEventArgs(exception, false));
         }
         this.Status = UpdateStatus.Problem;
     }
 }
Пример #6
0
        /// <summary>
        /// Downloads a file from the website using async
        /// </summary>
        /// <param name="URL">The URL to the file</param>
        /// <param name="path">The path to save the file at</param>
        /// <param name="method">The method to run once the download is done</param>
        /// <param name="useNewClient">Use a new client</param>
        /// <param name="client">A custom client(leave null to create a new one)</param>
        /// <returns>If the file was downloaded successfully</returns>
        public static bool DownloadFileAsync(string URL, string path, AsyncCompletedEventHandler method = null, bool useNewClient = true, WeebClient client = null)
        {
            try
            {
                if (useNewClient || client == null)
                {
                    WeebClient wc = new WeebClient();

                    wc.DownloadFileCompleted += new AsyncCompletedEventHandler(OnDownloadFile);
                    if (method != null)
                    {
                        wc.DownloadFileCompleted += method;
                    }
                    wc.DownloadFileAsync(new Uri(URL), path);
                    return(true);
                }

                client.DownloadFileAsync(new Uri(URL), path);
                return(true);
            }
            catch (Exception ex)
            {
                PointBlankLogging.LogError("Failed to download file via async from " + URL, ex, false, false);
                return(false);
            }
        }
Пример #7
0
        public bool StartDownload(AsyncCompletedEventHandler dlFinishedCallback,
                                  DownloadProgressChangedEventHandler dlProgressCallback,
                                  string URL,
                                  string SavePath)
        {
            Uri uri;

            try
            {
                uri = new Uri(URL);
            }
            catch (Exception)
            {
                return(false);
            }
            m_client.DownloadFileCompleted   += dlFinishedCallback;
            m_client.DownloadProgressChanged += dlProgressCallback;

            int chrindex = SavePath.LastIndexOf(@"/");

            if (chrindex == -1)
            {
                chrindex = SavePath.LastIndexOf(@"\");
            }

            string Path = SavePath.Substring(0, chrindex);

            System.IO.Directory.CreateDirectory(Path);

            m_client.DownloadFileAsync(uri, MyToolkit.ValidPath(SavePath));

            return(true);
        }
Пример #8
0
        private void GetChangeLogCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (InvokeRequired)
            {
                AsyncCompletedEventHandler myDelegate = new AsyncCompletedEventHandler(GetChangeLogCompleted);
                Invoke(myDelegate, new object[] { sender, e });
                return;
            }

            try
            {
                _appUpdate.GetChangeLogCompletedEvent -= GetChangeLogCompleted;

                if (e.Cancelled)
                {
                    return;
                }
                if (e.Error != null)
                {
                    throw (e.Error);
                }

                txtChangeLog.Text = _appUpdate.ChangeLog;
            }
            catch (Exception ex)
            {
                Runtime.MessageCollector.AddExceptionMessage(Language.strUpdateGetChangeLogFailed, ex);
            }
        }
Пример #9
0
        public static void DownloadFileAsync(string fileLocation,
                                             DownloadProgressChangedEventHandler downloadHandler,
                                             AsyncCompletedEventHandler downloadCompletedHandler, string programid = null)
        {
            try
            {
                using (ByteGuardWebClient byteguardWebClient = new ByteGuardWebClient())
                {
                    byteguardWebClient.CookieJar = CookieContainer;

                    byteguardWebClient.DownloadProgressChanged += downloadHandler;
                    //byteguardWebClient.DownloadDataCompleted += downloadCompletedHandler;
                    byteguardWebClient.DownloadFileCompleted += downloadCompletedHandler;

                    Uri postUri =
                        new Uri(
                            String.Format("{0}process.php?act=dlprogram&pid={1}",
                                          Variables.ByteGuardHost, programid));

                    lock (LockObject)
                    {
                        byteguardWebClient.DownloadFileAsync(postUri, fileLocation);
                    }
                }
            }
            catch
            {
                Variables.Containers.Main.SetStatus("Failed to download program, please try again shortly.", 1);
            }
        }
Пример #10
0
        public Form1()
        {
            InitializeComponent();

            thread1 = new Thread(new ThreadStart(this.threadEntryPoint));
            thread1_Thread1Completed += new AsyncCompletedEventHandler(thread1_Thread1Completed);
        }
Пример #11
0
        private void GetChangeLogCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (InvokeRequired)
            {
                var myDelegate = new AsyncCompletedEventHandler(GetChangeLogCompleted);
                Invoke(myDelegate, sender, e);
                return;
            }

            try
            {
                _appUpdate.GetChangeLogCompletedEvent -= GetChangeLogCompleted;

                if (e.Cancelled)
                {
                    return;
                }
                if (e.Error != null)
                {
                    throw e.Error;
                }

                txtChangeLog.Text = _appUpdate.ChangeLog.Replace("\n", Environment.NewLine);
            }
            catch (Exception ex)
            {
                Runtime.MessageCollector.AddExceptionMessage(Language.strUpdateGetChangeLogFailed, ex);
            }
        }
Пример #12
0
        /*!
         *  \brief Download the update installer to a user-defined file without blocking the current thread.
         *
         *  \param downloadCompleteFunc Function to be called when the download finishes.
         *
         *  \return True if the download process was successfully started, and false if the
         *  end-user canceled the dialog choosing where to save the downloading file to, or an
         *  error occurred.
         */
        public bool DownloadUpdateAsync(AsyncCompletedEventHandler downloadCompleteFunc)
        {
            DownloadFileCompleted += downloadCompleteFunc;

            var saveFile = new SaveFileDialog {
                Title            = "Save Download As",
                Filter           = "Windows Installer (*.msi)|*.msi",
                OverwritePrompt  = true,
                FileName         = "vp_lottery_setup",
                DefaultExt       = "msi",
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
            };
            var filedChosen = saveFile.ShowDialog();

            if (filedChosen == null || !filedChosen.Value)
            {
                return(false);
            }

            // Open and close file to ensure that it exists before downloading the data into it.
            var targetFile = saveFile.OpenFile();

            targetFile.Close();
            try {
                UpdateInstallerFile = saveFile.FileName;
                DownloadFileTaskAsync(AppMsiUri, UpdateInstallerFile);
                return(true);
            }
            catch (Exception e) {
                LogError(e.Message + " Target URI: " + AppMsiUri);
                return(false);
            }
        }
Пример #13
0
        private void GetAnnouncementInfoCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (InvokeRequired)
            {
                AsyncCompletedEventHandler myDelegate = new AsyncCompletedEventHandler(GetAnnouncementInfoCompleted);
                Invoke(myDelegate, new object[] { sender, e });
                return;
            }

            try
            {
                _appUpdate.GetAnnouncementInfoCompletedEvent -= GetAnnouncementInfoCompleted;

                if (e.Cancelled)
                {
                    return;
                }
                if (e.Error != null)
                {
                    throw (e.Error);
                }

                webBrowser.Navigate(_appUpdate.CurrentAnnouncementInfo.Address);
            }
            catch (Exception ex)
            {
                Runtime.MessageCollector.AddExceptionMessage(Language.strUpdateGetAnnouncementInfoFailed, ex);
            }
        }
    /// <summary>Downloads the resource with the specified URI to a local file, asynchronously.</summary>
    /// <param name="webClient">The WebClient.</param>
    /// <param name="address">The URI from which to download data.</param>
    /// <param name="fileName">The name of the local file that is to receive the data.</param>
    /// <returns>A Task that contains the downloaded data.</returns>
    public static Task DownloadFileTaskAsync(this WebClient webClient, Uri address, string fileName)
    {
        // Create the task to be returned
        var tcs = new TaskCompletionSource <object>(address);

        // Setup the callback event handler
        AsyncCompletedEventHandler completedHandler = null;

        completedHandler = (sender, e) => TaskServices.HandleEapCompletion(tcs, true, e, () => null, () =>
        {
            webClient.DownloadFileCompleted -= completedHandler;
        });
        webClient.DownloadFileCompleted += completedHandler;

        // Start the async operation.
        try
        {
            webClient.DownloadFileAsync(address, fileName, tcs);
        }
        catch
        {
            webClient.DownloadFileCompleted -= completedHandler;
            throw;
        }

        // Return the task that represents the async operation
        return(tcs.Task);
    }
        protected override async Task <bool> CheckUpdateCore()
        {
            UpdateCheckInfo       info = null;
            ApplicationDeployment ad   = ApplicationDeployment.CurrentDeployment;

            try {
                info = ad.CheckForDetailedUpdate();
            }
            catch (DeploymentDownloadException) {
                return(false);
            }
            catch (InvalidDeploymentException) {
                return(false);
            }
            catch (InvalidOperationException) {
                return(false);
            }
            if (!info.UpdateAvailable)
            {
                return(false);
            }
            bool handled = false;
            AsyncCompletedEventHandler handler = (sender, e) => {
                handled = true;
            };

            ad.UpdateCompleted += handler;
            ad.UpdateAsync();
            while (!handled)
            {
                await Task.Delay(100);
            }
            ad.UpdateCompleted -= handler;
            return(true);
        }
        public void AddAttachmentsShouldAddFilesCorrespondingToDifferentDataCollectors()
        {
            var filename  = "filename.txt";
            var filename1 = "filename1.txt";

            File.WriteAllText(Path.Combine(TempDirectoryPath, filename), string.Empty);
            File.WriteAllText(Path.Combine(TempDirectoryPath, filename1), string.Empty);

            this.attachmentManager.Initialize(this.sessionId, TempDirectoryPath, this.messageSink.Object);

            var datacollectioncontext = new DataCollectionContext(this.sessionId);
            var friendlyName          = "TestDataCollector";
            var uri  = new Uri("datacollector://Company/Product/Version");
            var uri1 = new Uri("datacollector://Company/Product/Version1");

            EventWaitHandle waitHandle = new AutoResetEvent(false);
            var             handler    = new AsyncCompletedEventHandler((a, e) => { waitHandle.Set(); });
            var             dataCollectorDataMessage = new FileTransferInformation(datacollectioncontext, Path.Combine(TempDirectoryPath, filename), false);

            this.attachmentManager.AddAttachment(dataCollectorDataMessage, handler, uri, friendlyName);

            // Wait for file operations to complete
            waitHandle.WaitOne(Timeout);

            waitHandle.Reset();
            dataCollectorDataMessage = new FileTransferInformation(datacollectioncontext, Path.Combine(TempDirectoryPath, filename1), false);
            this.attachmentManager.AddAttachment(dataCollectorDataMessage, handler, uri1, friendlyName);

            // Wait for file operations to complete
            waitHandle.WaitOne(Timeout);

            Assert.AreEqual(1, this.attachmentManager.AttachmentSets[datacollectioncontext][uri].Attachments.Count);
            Assert.AreEqual(1, this.attachmentManager.AttachmentSets[datacollectioncontext][uri1].Attachments.Count);
        }
        public void GetAttachmentsShouldNotReturnAttachmentsAfterCancelled()
        {
            var fileHelper = new Mock <IFileHelper>();
            var testableAttachmentManager = new TestableDataCollectionAttachmentManager(fileHelper.Object);
            var attachmentPath            = Path.Combine(TempDirectoryPath, "filename.txt");

            File.WriteAllText(attachmentPath, string.Empty);
            var datacollectioncontext = new DataCollectionContext(this.sessionId);
            var friendlyName          = "TestDataCollector";
            var uri = new Uri("datacollector://Company/Product/Version");
            var dataCollectorDataMessage = new FileTransferInformation(datacollectioncontext, attachmentPath, true);
            var waitHandle = new AutoResetEvent(false);
            var handler    = new AsyncCompletedEventHandler((a, e) => { Assert.Fail("Handler shouldn't be called since operation is canceled."); });

            // We cancel the operation in the actual operation. This ensures the follow up task to is never called, attachments
            // are not added.
            Action cancelAddAttachment = () => testableAttachmentManager.Cancel();

            fileHelper.Setup(fh => fh.MoveFile(It.IsAny <string>(), It.IsAny <string>())).Callback(cancelAddAttachment);
            testableAttachmentManager.Initialize(this.sessionId, TempDirectoryPath, this.messageSink.Object);
            testableAttachmentManager.AddAttachment(dataCollectorDataMessage, handler, uri, friendlyName);

            // Wait for the attachment transfer tasks to complete
            var result = testableAttachmentManager.GetAttachments(datacollectioncontext);

            Assert.AreEqual(0, result[0].Attachments.Count);
        }
Пример #18
0
        IEnumerator <Task <AsyncCompletedEventArgs> > FetchOperationAsyncHelper(object state, CancellationToken token, int timeout, Action continuator)
        {
            var tcs = new TaskCompletionSource <AsyncCompletedEventArgs>();
            // prepare the timeout
            CancellationToken newToken;

            if (timeout != Timeout.Infinite)
            {
                var cts = CancellationTokenSource.CreateLinkedTokenSource(token);
                TaskExt.CancelAfterEx(cts, timeout * 1000);
                newToken = cts.Token;
            }
            else
            {
                newToken = token;
            }
            /* handle completion */
            AsyncCompletedEventHandler handler = (sender, args) =>
            {
                if (args.Cancelled)
                {
                    tcs.TrySetCanceled();
                }
                else if (args.Error != null)
                {
                    tcs.SetException(args.Error);
                }
                else
                {
                    tcs.SetResult(args);
                }
            };

            this.FetchOperationCompleted += handler;
            try
            {
                using (newToken.Register(() =>
                {
                    try
                    {
                        tcs.SetCanceled();
                    }
                    catch (InvalidOperationException)
                    {
                        /* cancel when already finished, does not matter */
#if DEBUG
                        Tracing.WarningDAL("Canceled async db operation, when it has already completed.");
#endif
                    }
                }, useSynchronizationContext: false))
                {
                    this.StartFetchOperation(state);
                    yield return(tcs.Task.Continuation(continuator));
                }
            }
            finally
            {
                this.FetchOperationCompleted -= handler;
            }
        }
Пример #19
0
        /// <summary>
        /// This method can be used to download binary data from a URL. It is an ansynchronous method that can report progress.
        /// </summary>
        /// <returns></returns>
        public async Task <byte[]> GetBytesFromUrl(
            string url,
            ICredentials credential = null,
            DownloadProgressChangedEventHandler downloadProgressHandler = null,
            AsyncCompletedEventHandler downloadCompleteHandler          = null)
        {
            using (var webClient = new WebClient())
            {
                if (credential != null)
                {
                    webClient.Credentials = credential;
                }

                if (downloadProgressHandler != null)
                {
                    webClient.DownloadProgressChanged += downloadProgressHandler;
                }
                if (downloadCompleteHandler != null)
                {
                    webClient.DownloadFileCompleted += downloadCompleteHandler;
                }

                return(await webClient.DownloadDataTaskAsync(url));
            }
        }
Пример #20
0
        /// <inheritdoc/>
        public void AddAttachment(FileTransferInformation fileTransferInfo, AsyncCompletedEventHandler sendFileCompletedCallback, Uri uri, string friendlyName)
        {
            ValidateArg.NotNull(fileTransferInfo, nameof(fileTransferInfo));

            if (string.IsNullOrEmpty(this.SessionOutputDirectory))
            {
                if (EqtTrace.IsErrorEnabled)
                {
                    EqtTrace.Error(
                        "DataCollectionAttachmentManager.AddAttachment: Initialize not invoked.");
                }

                return;
            }

            if (!this.AttachmentSets.ContainsKey(fileTransferInfo.Context))
            {
                var uriAttachmentSetMap = new Dictionary <Uri, AttachmentSet>();
                this.AttachmentSets.Add(fileTransferInfo.Context, uriAttachmentSetMap);
                this.attachmentTasks.Add(fileTransferInfo.Context, new List <Task>());
            }

            if (!this.AttachmentSets[fileTransferInfo.Context].ContainsKey(uri))
            {
                this.AttachmentSets[fileTransferInfo.Context].Add(uri, new AttachmentSet(uri, friendlyName));
            }

            this.AddNewFileTransfer(fileTransferInfo, sendFileCompletedCallback, uri, friendlyName);
        }
Пример #21
0
        private void GetUpdateInfoCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (InvokeRequired)
            {
                AsyncCompletedEventHandler myDelegate = GetUpdateInfoCompleted;
                Invoke(myDelegate, sender, e);
                return;
            }

            try
            {
                _appUpdate.GetUpdateInfoCompletedEvent -= GetUpdateInfoCompleted;

                btnTestProxy.Enabled = true;
                btnTestProxy.Text    = Language.strButtonTestProxy;

                if (e.Cancelled)
                {
                    return;
                }
                if (e.Error != null)
                {
                    throw e.Error;
                }

                CTaskDialog.ShowCommandBox(this, Convert.ToString(Application.ProductName),
                                           Language.strProxyTestSucceeded, "", Language.strButtonOK, false);
            }
            catch (Exception ex)
            {
                CTaskDialog.ShowCommandBox(this, Convert.ToString(Application.ProductName), Language.strProxyTestFailed,
                                           MiscTools.GetExceptionMessageRecursive(ex), "", "", "", Language.strButtonOK, false, ESysIcons.Error,
                                           0);
            }
        }
        /// <summary>
        /// Create an instance of the DatabaseAutomationRunner window
        /// </summary>
        public DatabaseAutomationRunner(ModpackSettings modpackSettings, Logfiles logfile) : base(modpackSettings, logfile)
        {
            InitializeComponent();
            DownloadProgressChanged = WebClient_DownloadProgressChanged;
            DownloadDataCompleted   = WebClient_DownloadDataComplted;
            DownloadFileCompleted   = WebClient_TransferFileCompleted;
            UploadFileCompleted     = WebClient_UploadFileCompleted;
            UploadProgressChanged   = WebClient_UploadProgressChanged;
            RelhaxProgressChanged   = RelhaxProgressReport_ProgressChanged;
            ProgressChanged         = GenericProgressChanged;
            Settings = AutomationSettings;

            //https://stackoverflow.com/questions/7712137/array-containing-methods
            settingsMethods = new Action[]
            {
                () => OpenLogWindowOnStartupSetting_Click(null, null),
                () => BigmodsUsernameSetting_TextChanged(null, null),
                () => BigmodsPasswordSetting_TextChanged(null, null),
                () => DumpParsedMacrosPerSequenceRunSetting_Click(null, null),
                () => DumpEnvironmentVariablesAtSequenceStartSetting_Click(null, null),
                () => SuppressDebugMessagesSetting_Click(null, null),
                () => AutomamtionDatabaseSelectedBranchSetting_TextChanged(null, null),
                () => SelectDBSaveLocationSetting_TextChanged(null, null),
                () => UseLocalRunnerDatabaseSetting_Click(null, null),
                () => LocalRunnerDatabaseRootSetting_TextChanged(null, null),
                () => SelectWoTInstallLocationSetting_TextChanged(null, null)
            };
        }
Пример #23
0
		/// <see cref="IAsyncWebClient.DownloadFileAsync"/>
		public Task DownloadFileAsync(Uri address, string fileName, IProgress<DownloadProgressChangedEventArgs> progress, CancellationToken cancellationToken)
		{
			cancellationToken.Register(() => _webClient.CancelAsync());

			var cookie = Guid.NewGuid();
			var tcs = new TaskCompletionSource<object>();

			DownloadProgressChangedEventHandler progressHandler = CreateProgressHandler(cookie, progress);
			if (progress != null)
				_webClient.DownloadProgressChanged += progressHandler;

			AsyncCompletedEventHandler completedHandler = null;
			completedHandler = (o, e) =>
			{
				if (!Equals(e.UserState, cookie))
					return;

				_webClient.DownloadProgressChanged -= progressHandler;
				_webClient.DownloadFileCompleted -= completedHandler;

				tcs.TrySetFromEventArgs(e);
			};
			_webClient.DownloadFileCompleted += completedHandler;

			_webClient.DownloadFileAsync(address, fileName, cookie);
			return tcs.Task;
		}
Пример #24
0
        /// <summary>
        ///     Handle finished download, move file from temporary to target location
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Finished(object sender, AsyncCompletedEventArgs e)
        {
            try
            {
                Logger.Log(LogLevel.Info, "FileDownloadProgressBar", "Download finished!", Url);
                // Move to the correct location
                if (File.Exists(Targetlocation))
                {
                    File.Delete(Targetlocation);
                }
                File.Move(_tmplocation, Targetlocation);
            }
            catch (Exception ex)
            {
                // TODO: figure out what locks these files
                Logger.Log(LogLevel.Severe, "FileDownloadProgressBar", "Could not replace file " + Targetlocation, ex.Message);
            }


            AsyncCompletedEventHandler handler = DownloadCompleted;

            if (handler != null)
            {
                handler(sender, e);
            }
        }
        public void AddAttachmentShouldAddNewFileTransferAndCopyFileToOutputDirectoryIfDeleteFileIsFalse()
        {
            var filename = "filename.txt";

            File.WriteAllText(Path.Combine(TempDirectoryPath, filename), string.Empty);


            this.attachmentManager.Initialize(this.sessionId, TempDirectoryPath, this.messageSink.Object);

            var datacollectioncontext = new DataCollectionContext(this.sessionId);
            var friendlyName          = "TestDataCollector";
            var uri = new Uri("datacollector://Company/Product/Version");

            EventWaitHandle waitHandle = new AutoResetEvent(false);
            var             handler    = new AsyncCompletedEventHandler((a, e) => { waitHandle.Set(); });
            var             dataCollectorDataMessage = new FileTransferInformation(datacollectioncontext, Path.Combine(TempDirectoryPath, filename), false);


            this.attachmentManager.AddAttachment(dataCollectorDataMessage, handler, uri, friendlyName);

            // Wait for file operations to complete
            waitHandle.WaitOne(Timeout);

            Assert.IsTrue(File.Exists(Path.Combine(TempDirectoryPath, filename)));
            Assert.IsTrue(File.Exists(Path.Combine(TempDirectoryPath, this.sessionId.Id.ToString(), filename)));
            Assert.AreEqual(1, this.attachmentManager.AttachmentSets[datacollectioncontext][uri].Attachments.Count);
        }
Пример #26
0
        private static FileInfo DownloadFileFromUrlToPathRaw(string url, string path, WebClient webClient)
        {
            if (ProgressDisplay.CanUseConsole)
            {
                using (var display = new ProgressDisplay(0))
                {
                    DownloadProgressChangedEventHandler downloadProgress  = (sender, e) => { display.Update(e.BytesReceived, e.TotalBytesToReceive); };
                    AsyncCompletedEventHandler          downloadCompleted = (sender, e) =>
                    {
                        lock (e.UserState)
                        {
                            Monitor.Pulse(e.UserState);
                        }
                    };

                    var syncObj = new object();
                    lock (syncObj)
                    {
                        webClient.DownloadProgressChanged += downloadProgress;
                        webClient.DownloadFileCompleted   += downloadCompleted;

                        webClient.DownloadFileAsync(new Uri(url), path, syncObj);
                        Monitor.Wait(syncObj);

                        webClient.DownloadProgressChanged -= downloadProgress;
                        webClient.DownloadFileCompleted   -= downloadCompleted;
                    }
                }
            }
            else
            {
                AsyncCompletedEventHandler downloadCompleted = (sender, e) =>
                {
                    lock (e.UserState)
                    {
                        if (e.Error != null)
                        {
                            Log.Error("Download failed.");
                            Log.Exception(e.Error);
                        }

                        Monitor.Pulse(e.UserState);
                    }
                };

                var syncObj = new object();
                lock (syncObj)
                {
                    webClient.DownloadFileCompleted += downloadCompleted;

                    webClient.DownloadFileAsync(new Uri(url), path, syncObj);
                    Monitor.Wait(syncObj);

                    webClient.DownloadFileCompleted -= downloadCompleted;
                }
            }

            return(new FileInfo(path));
        }
Пример #27
0
    //Download File Async custom method
    public void DldFile(string url, string fileName, string localPath, AsyncCompletedEventHandler completedName, DownloadProgressChangedEventHandler progressName)
    {
        WebClient webClient = new WebClient();

        webClient.DownloadFileAsync(new Uri(url), localPath + "\\" + fileName);
        webClient.DownloadFileCompleted   += new AsyncCompletedEventHandler(completedName);
        webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(progressName);
    }
Пример #28
0
        public void DownloadInstaller(DownloadProgressChangedEventHandler onData,
                                      AsyncCompletedEventHandler onFinish)
        {
            _downloader.DownloadProgressChanged += onData;
            _downloader.DownloadFileCompleted   += onFinish;

            _downloader.DownloadFileAsync(_installerURI, InstallerFile);
        }
Пример #29
0
 public static ApplicationDeployment DoUpdateAsync(AsyncCompletedEventHandler onComplete = null, DeploymentProgressChangedEventHandler onProgress = null)
 {
     var ad = ApplicationDeployment.CurrentDeployment;
     if (onComplete != null) ad.UpdateCompleted += onComplete;
     if (onProgress != null) ad.UpdateProgressChanged += onProgress;
     ad.UpdateAsync();
     return ad;
 }
Пример #30
0
        private void GetImagesinUrl1(HttpContext context)
        {
            string    url    = context.Request.QueryString["url"];
            Regex     img    = new Regex("<img.+?src=[\"'](.+?)[\"'].+?>", RegexOptions.IgnoreCase);
            Regex     src    = new Regex(@"src=(?:(['""])(?<src>(?:(?!\1).)*)\1|(?<src>[^\s>]+))", RegexOptions.IgnoreCase | RegexOptions.Singleline);
            WebClient source = new WebClient();
            string    value  = source.DownloadString(new Uri(url));

            if (!string.IsNullOrEmpty(value))
            {
                MatchCollection matches = img.Matches(value);
                if (matches.Count > 0)
                {
                    string rpath = Common.RelTemp + Common.UserID;
                    string path  = Common.Temp + Common.UserID;
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    else
                    {
                        string[] files = Directory.GetFiles(path);
                        foreach (string file in files)
                        {
                            File.Delete(file);
                        }
                    }
                    int i = 0;
                    Dictionary <int, bool>     _dict    = new Dictionary <int, bool>();
                    List <string>              paths    = new List <string>();
                    AsyncCompletedEventHandler callback = (sender, e) =>
                    {
                        dynamic dyn = (dynamic)e.UserState;
                        _dict[dyn.i] = true;
                        string rfn = rpath + dyn.i + ".jpg";
                        paths.Add(rfn);
                    };
                    foreach (Match match in matches)
                    {
                        string    imgUrl = match.Groups[1].Value;
                        WebClient client = new WebClient();
                        client.DownloadFileCompleted += callback;
                        string  fn  = path + "\\" + i + ".jpg";
                        dynamic dyn = new ExpandoObject();
                        dyn.fn = fn;
                        dyn.i  = i;
                        client.DownloadFileAsync(new Uri(imgUrl), fn, dyn);
                        _dict.Add(i, false);
                        i++;
                    }
                    while (_dict.ContainsValue(false))
                    {
                        Thread.Sleep(500);
                    }
                    context.WriteJsonP(JsonConvert.SerializeObject(paths, Formatting.Indented, Common.JsonSerializerSettings));
                }
            }
        }
        public async Task <bool> DownloadPodcastAsync(
            IPodcastEpisode episode, string directoryOut, AsyncCompletedEventHandler completedDownloadEvent = null,
            DownloadProgressChangedEventHandler downloadProgressChangedEvent = null, bool downloadInsertions = false)
        {
            try
            {
                if (string.IsNullOrEmpty(directoryOut))
                {
                    return(false);
                }

                if (!_fileHelper.DirectoryExists(directoryOut))
                {
                    _fileHelper.CreateDirectory(directoryOut);
                }

                if (episode is Episode naoOuvoEpisode && _fileHelper.DirectoryExists(directoryOut))
                {
                    var archiveName = naoOuvoEpisode.Url.Substring(naoOuvoEpisode.Url.LastIndexOf("/") + 1);

                    if (currentFilesDownloading.Any(name => name.Equals(archiveName, StringComparison.CurrentCultureIgnoreCase)))
                    {
                        return(false);
                    }

                    var httpclient = new HttpClient()
                    {
                        Timeout = (new TimeSpan(5, 0, 0))
                    };

                    var client = new WebApiClient(httpclient, _fileHelper);

                    currentFilesDownloading.Add(archiveName);
                    directoryOut = directoryOut.EndsWith("\\") ? directoryOut : directoryOut + "\\";

                    if (downloadInsertions)
                    {
                        await DownloadNaoOuvoInsertions(naoOuvoEpisode, directoryOut, archiveName);
                    }

                    var filePath = string.Concat(directoryOut, archiveName);

                    await client.GetAsync(naoOuvoEpisode.Url, filePath);

                    currentFilesDownloading.Remove(archiveName);
                    completedDownloadEvent?.Invoke(null, null);

                    return(true);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error on NaoOuvo download.\n\nDetails{ex.Message}");
                return(false);
            }

            return(false);
        }
Пример #32
0
        public static void FileRequestAsync(string url, string outputFile,
            DownloadProgressChangedEventHandler progressCallback,
            AsyncCompletedEventHandler completeCallback)
        {
            var wc = new WebClient();
            if (_proxy != null)
                wc.Proxy = _proxy;

            wc.DownloadFileCompleted += completeCallback;
            wc.DownloadProgressChanged += progressCallback;
            wc.DownloadFileAsync(new System.Uri(url), outputFile);
        }
 public SizePropertyBag(IVirtualFolder owner, AsyncCompletedEventHandler completed)
 {
     if (owner is ICloneable)
     {
         this.FOwner = (IVirtualFolder) ((ICloneable) owner).Clone();
     }
     else
     {
         this.FOwner = owner;
     }
     this.FOwnerParent = owner.Parent as IVirtualCachedFolder;
     this.FCompleted = completed;
 }
Пример #34
0
 /// <summary>
 /// Загружает файл (Асинхронно)
 /// </summary>
 /// <param name="saveToFileName"></param>
 /// <param name="url"></param>
 /// <param name="callback"></param>
 /// <param name="onProgress"></param>
 public static void loadFileAsync(String saveToFileName, String url,
                                  AsyncCompletedEventHandler callback,
                                  DownloadProgressChangedEventHandler onProgress) {
   WebClient wc = new WebClient();
   wc.OpenReadCompleted += new OpenReadCompletedEventHandler((Object sender, OpenReadCompletedEventArgs e) => {
     //throw new NotImplementedException();
     //FileStream  
     //File.WriteAllBytes();
   });
   if (onProgress != null)
     wc.DownloadProgressChanged += onProgress;
   wc.OpenReadAsync(new Uri(url, UriKind.RelativeOrAbsolute));
 }
Пример #35
0
 public async Task DownloadAudioAync(Song song, string path, DownloadProgressChangedEventHandler ProgressChanged, AsyncCompletedEventHandler DownloadSongCallback)
 {
     try
     {
         WebClient Client = new WebClient();
         hashCodeConnection.Add(Client.GetHashCode(), song.GetHashCode());
         Client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadSongCallback);
         Client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFileCallback);
         Client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
         await Client.DownloadFileTaskAsync(song.Uri, path);
     }
     catch
     { }
 }
 public static void UpdateList(bool silent, bool installedOnly, DownloadProgressChangedEventHandler downloadProgressChanged, AsyncCompletedEventHandler downloadFileCompleted)
 {
   if (!installedOnly)
   {
     DownloadExtensionIndex(downloadProgressChanged, downloadFileCompleted);
   }
   DownloadInfo dlg = new DownloadInfo();
   dlg.silent = silent;
   dlg.installedOnly = installedOnly;
   if (dlg.ShowDialog() == DialogResult.OK && !installedOnly)
   {
     ApplicationSettings.Instance.LastUpdate = DateTime.Now;
     ApplicationSettings.Instance.Save();
   }
 }
Пример #37
0
    /// <summary>
    /// Загружает файл (Асинхронно)
    /// </summary>
    /// <param name="pToFileName"></param>
    /// <param name="pURL"></param>
    /// <param name="pOnCmpltHndlr"></param>
    /// <param name="pOnPrgHndlr"></param>
    public static void loadFileAsync(String pToFileName, String pURL,
                                AsyncCompletedEventHandler pOnCmpltHndlr,
                                DownloadProgressChangedEventHandler pOnPrgHndlr) {

      WebClient wc = new WebClient();
      if(pOnPrgHndlr != null)
        wc.DownloadProgressChanged += pOnPrgHndlr;
      wc.DownloadFileCompleted += new AsyncCompletedEventHandler((object sender, AsyncCompletedEventArgs e) => 
      {
        if(pOnCmpltHndlr != null)
          pOnCmpltHndlr(sender, e);
      });
      wc.Headers.Set(HttpRequestHeader.Cookie, ajaxUTL.csSessionIdName+"="+ajaxUTL.sessionID.Value);
      String vURL = pURL + "&pdummy=" + new Guid().ToString();
      wc.DownloadFileAsync(new Uri(vURL), pToFileName);
    }
Пример #38
0
        public ImageProcessingManager()
        {
            processWorkerDelegate = new Action<Queue<KeyValuePair<string, string>>, IEnumerable<IProcessingPlugin>, IOutputPlugin, AsyncOperation>(ProcessWorker);
            processAsyncTaskProgressChangedDelegate = new SendOrPostCallback(ProcessAsyncTaskProgressChanged);
            processAsyncProgressChangedDelegate = new SendOrPostCallback(ProcessAsyncProgressChanged);
            processAsyncStateChangedDelegate = new SendOrPostCallback(ProcessAsyncStateChanged);
            processAsyncCompletedDelegate = new SendOrPostCallback(ProcessAsyncCompleted);
            processingProgressForm_CancelProcessDelegate = new EventHandler<AsyncEventArgs>(processingProgressForm_CancelProcess);

            imageProcessor.ProcessProgressChanged += new ProgressChangedEventHandler(imageProcessor_ProcessProgressChanged);
            imageProcessor.ProcessCompleted += new AsyncCompletedEventHandler(imageProcessor_ProcessCompleted);

            ProcessTaskProgressChanged += new EventHandler<ProcessTaskProgressChangedEventArgs>(ImageProcessingManager_ProcessTaskProgressChanged);
            ProcessProgressChanged += new ProgressChangedEventHandler(ImageProcessingManager_ProcessProgressChanged);
            ProcessStateChanged += new EventHandler<ProcessStateChangedEventArgs>(ImageProcessingManager_ProcessStateChanged);
            ProcessCompleted += new AsyncCompletedEventHandler(ImageProcessingManager_ProcessCompleted);
        }
Пример #39
0
 public Status DownloadSong(List<Song> listToDownload, DownloadProgressChangedEventHandler ProgressChanged, AsyncCompletedEventHandler DownloadSongCallback)
 {
     string folderName = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
     string pathString = Path.Combine(folderName, "VVKMusic");
     if (!File.Exists(pathString)) Directory.CreateDirectory(pathString);
     string folder = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic) + @"\VVKMusic\";
     count = listToDownload.Count;
     foreach (Song song in listToDownload)
     {
         string fileName = song.Artist + "-" + song.Title + ".mp3";
         if (DownloadAudioAync(song, @folder + fileName, ProgressChanged, DownloadSongCallback).Exception != null)
         {
             return Status.Error;
         }
         song.DownloadedUri = new Uri(@folder + @fileName);
     }
     return Status.Ok;
 }
Пример #40
0
        private void DownloadFile(Uri remoteUri, string localDest,
			AsyncCompletedEventHandler finished=null)
        {
            using (var downloadClient = new WebClient ()) {
                try {
                    FileHelper.EnsureFileDirExists (localDest);
                    logger.DebugFormat ("Downloading file from {0} to {1}",
                        remoteUri, localDest);

                    downloadClient.DownloadProgressChanged += onProgressChanged;
                    downloadClient.DownloadFileCompleted += finished ?? onFileDownloaded;
                    downloadClient.DownloadFileAsync (remoteUri, localDest);
                    onDownloadStarted();
                }
                catch (Exception ex) {
                    logger.Fatal ("Downloading update failed", ex);
                    onDownloadFailed (ex);
                }
            }
        }
Пример #41
0
        public async Task<bool> DownloadUpdate(DownloadProgressChangedEventHandler progressEventHandler,
            AsyncCompletedEventHandler progressCompleteEventHandler)
        {
            try
            {
                if (Url != null && FileName != null)
                {
                    string filePath = $"Res\\{FileName}.zip";
                    //We download our update.
                    //HttpClient client = new HttpClient();
                    WebClient wclient = new WebClient();

                    //var input = await client.GetByteArrayAsync(Url);

                    //We Recreate our previous Res Folder
                    if (Directory.Exists("Res"))
                        Directory.Delete("Res", true);
                    Directory.CreateDirectory("Res");
                    //using (var fileStream = File.Create(filePath))
                    //{
                    //    fileStream.Write(input, 0, input.Length);
                    //}
                    wclient.DownloadProgressChanged += progressEventHandler;
                    wclient.DownloadFileCompleted += progressCompleteEventHandler;
                    wclient.DownloadFileAsync(new Uri(Url), filePath);
                    return File.Exists(filePath);
                }
                else
                {
                    //Something went wrong.
                    return false;
                }
            }
            catch (Exception)
            {
                //Something really went wrong.
                return false;
            }
        }
 static void DownloadExtensionIndex(DownloadProgressChangedEventHandler downloadProgressChanged, AsyncCompletedEventHandler downloadFileCompleted)
 {
   DownloadFile dlg = null;
   try
   {
     tempUpdateIndex = Path.GetTempFileName();
     dlg = new DownloadFile();
     if (downloadProgressChanged != null) dlg.Client.DownloadProgressChanged += downloadProgressChanged;
     if (downloadFileCompleted != null) dlg.Client.DownloadFileCompleted += downloadFileCompleted;
     dlg.Client.DownloadFileCompleted += UpdateIndex_DownloadFileCompleted;
     dlg.StartDownload(UpdateIndexUrl, tempUpdateIndex);
   }
   catch (Exception ex)
   {
     MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
   }
   finally
   {
     if (downloadProgressChanged != null) dlg.Client.DownloadProgressChanged -= downloadProgressChanged;
     if (downloadFileCompleted != null) dlg.Client.DownloadFileCompleted -=downloadFileCompleted;
     dlg.Client.DownloadFileCompleted -= UpdateIndex_DownloadFileCompleted;
     File.Delete(tempUpdateIndex);
   }
 }
 /// <summary>
 ///     Downloads a file async
 /// </summary>
 /// <param name="downloadLink"></param>
 /// <param name="filename"></param>
 /// <param name="onProgress">can be null</param>
 /// <param name="onComplete">can be null</param>
 public static void DownloadFileAsync(string downloadLink, string filename,
     DownloadProgressChangedEventHandler onProgress,
     AsyncCompletedEventHandler onComplete)
 {
     WebClient webClient = new WebClient();
     try
     {
         MainConsole.Instance.Warn("Downloading new file from " + downloadLink + " now into file " + filename +
                                   ".");
         if (onProgress != null)
             webClient.DownloadProgressChanged += onProgress;
         if (onComplete != null)
             webClient.DownloadFileCompleted += onComplete;
         webClient.DownloadFileAsync(new Uri(downloadLink), filename);
     }
     catch (Exception)
     {
     }
 }
 private void FileDownload_Load(object sender, EventArgs e)
 {
     ProgressChanged += new DownloadProgressChangedEventHandler(FileDownload_ProgressChanged);
     DownloadComplete += new AsyncCompletedEventHandler(FileDownload_DownloadComplete);
 }
 public static string GetPackageLocation(PackageClass packageClass, DownloadProgressChangedEventHandler downloadProgressChanged, AsyncCompletedEventHandler downloadFileCompleted)
 {
   string newPackageLoacation = packageClass.GeneralInfo.Location;
   if (!File.Exists(newPackageLoacation))
   {
     newPackageLoacation = packageClass.LocationFolder + packageClass.GeneralInfo.Id + ".mpe2";
     if (!File.Exists(newPackageLoacation))
     {
       if (!string.IsNullOrEmpty(packageClass.GeneralInfo.OnlineLocation))
       {
         DownloadFile dlg = null;
         try
         {
           newPackageLoacation = Path.GetTempFileName();
           dlg = new DownloadFile();
           if (downloadProgressChanged != null) dlg.Client.DownloadProgressChanged += downloadProgressChanged;
           if (downloadFileCompleted != null) dlg.Client.DownloadFileCompleted += downloadFileCompleted;
           dlg.StartDownload(packageClass.GeneralInfo.OnlineLocation, newPackageLoacation);
         }
         catch (Exception ex)
         {
           MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
         finally
         {
           if (downloadProgressChanged != null) dlg.Client.DownloadProgressChanged -= downloadProgressChanged;
           if (downloadFileCompleted != null) dlg.Client.DownloadFileCompleted -= downloadFileCompleted;
         }
       }
     }
   }
   return newPackageLoacation;
 }
Пример #46
0
        private void GetUpdateInfoCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (InvokeRequired)
            {
                var myDelegate = new AsyncCompletedEventHandler(GetUpdateInfoCompleted);
                Invoke(myDelegate, sender, e);
                return;
            }

            try
            {
                _appUpdate.GetUpdateInfoCompletedEvent -= GetUpdateInfoCompleted;

                lblInstalledVersion.Text = Application.ProductVersion;
                lblInstalledVersion.Visible = true;
                lblInstalledVersionLabel.Visible = true;
                btnCheckForUpdate.Visible = true;

                if (e.Cancelled)
                {
                    return;
                }
                if (e.Error != null)
                {
                    throw e.Error;
                }

                if (_appUpdate.IsUpdateAvailable())
                {
                    lblStatus.Text = Language.strUpdateAvailable;
                    lblStatus.ForeColor = Color.OrangeRed;
                    pnlUpdate.Visible = true;

                    var updateInfo = _appUpdate.CurrentUpdateInfo;
                    lblLatestVersion.Text = updateInfo.Version.ToString();
                    lblLatestVersionLabel.Visible = true;
                    lblLatestVersion.Visible = true;

                    if (updateInfo.ImageAddress == null || string.IsNullOrEmpty(updateInfo.ImageAddress.ToString()))
                    {
                        pbUpdateImage.Visible = false;
                    }
                    else
                    {
                        pbUpdateImage.ImageLocation = updateInfo.ImageAddress.ToString();
                        pbUpdateImage.Tag = updateInfo.ImageLinkAddress;
                        pbUpdateImage.Visible = true;
                    }

                    _appUpdate.GetChangeLogCompletedEvent += GetChangeLogCompleted;
                    _appUpdate.GetChangeLogAsync();

                    btnDownload.Focus();
                }
                else
                {
                    lblStatus.Text = Language.strNoUpdateAvailable;
                    lblStatus.ForeColor = Color.ForestGreen;

                    if (_appUpdate.CurrentUpdateInfo != null)
                    {
                        var updateInfo = _appUpdate.CurrentUpdateInfo;
                        if (updateInfo.IsValid && updateInfo.Version != null)
                        {
                            lblLatestVersion.Text = updateInfo.Version.ToString();
                            lblLatestVersionLabel.Visible = true;
                            lblLatestVersion.Visible = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                lblStatus.Text = Language.strUpdateCheckFailedLabel;
                lblStatus.ForeColor = Color.OrangeRed;

                Runtime.MessageCollector.AddExceptionMessage(Language.strUpdateCheckCompleteFailed, ex);
            }
        }
Пример #47
0
        /// <summary>
        /// Create a new form instance.
        /// </summary>
        public FormDownload()
        {
            InitializeComponent();

            this.client.DownloadFileCompleted += this.OnDownloadCompleted;
            this.client.DownloadProgressChanged += this.OnDownloadProgressChanged;

            this.delegateProgressChanged = new DownloadProgressChangedEventHandler(this.OnDownloadProgressChanged);
            this.delegateDownloadCompleted = new AsyncCompletedEventHandler(this.OnDownloadCompleted);
            this.delegateDownloadError = new WaitCallback(this.DownloadError);

            this.formatting.SetFont(this);
        }
Пример #48
0
        public void Download(DownloadProgressChangedEventHandler progressHandler = null, AsyncCompletedEventHandler completedHandler = null)
        {
            IsDownloaded = false;
            if (!Directory.Exists(BasePath))
            {
                try
                {
                    Directory.CreateDirectory(BasePath);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    MessageBox.Show(Strings.CantCreateDLDir, Strings.Error, MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }

            using (var wc = new WebClient())
            {
                if (progressHandler != null) wc.DownloadProgressChanged += progressHandler;
                if (completedHandler != null) wc.DownloadFileCompleted += completedHandler;
                wc.DownloadFileAsync(new Uri(Properties.Resources.RootAddress + Filename), BasePath + Filename);
            }
        }
Пример #49
0
        /* Downloads latest release.
         * Throws UpdaterException if error occurs.
         */
        public static void Download(AsyncCompletedEventHandler completedHandler = null, DownloadProgressChangedEventHandler progressHandler = null)
        {
            if (Latest != null)
            {
                if (Latest.IsDownloaded || Latest.IsDownloading)
                    throw new UpdaterException(L10n.Message("Download completed or still in progress"));

                Latest.Download(completedHandler, progressHandler);
            }
        }
Пример #50
0
            /* Downloads release.
             * Throws UpdaterException if error occurs.
             */
            public void Download(AsyncCompletedEventHandler completedHandler, DownloadProgressChangedEventHandler progressHandler)
            {
                if (Client != null)
                    throw new UpdaterException(L10n.Message("Download already in progress"));
                if (DownloadFile != null)
                    throw new UpdaterException(L10n.Message("Download already completed"));

                try
                {
                    // Initialize web client.
                    Client = new UpdaterWebClient();
                    Client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadCompleted);
                    if (completedHandler != null)
                        Client.DownloadFileCompleted += new AsyncCompletedEventHandler(completedHandler);
                    if (progressHandler != null)
                        Client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(progressHandler);

                    // Create download file.
                    DownloadFile = Path.Combine(Path.GetTempPath(), PackageFileName);

                    // Start download.
                    Client.DownloadFileAsync(URI, DownloadFile);
                }
                catch (Exception e)
                {
                    Dispose();
                    throw new UpdaterException(e.Message, e);
                }
            }
Пример #51
0
		public void Download(string dataPath, AsyncCompletedEventHandler callback) {
			try {
				using(WebClient client = new WebClient()) {
					FileInfo dest = new FileInfo(Path.Combine(dataPath, "Updates", this.Latest.FileName));
					if(!dest.Directory.Exists) {
						dest.Directory.Create();
					}
					client.DownloadFileCompleted += delegate(object sender, AsyncCompletedEventArgs e) {
						if(!e.Cancelled && (e.Error == null)) {
							this.Unzip(dest.FullName);
							callback(sender, e);
						}
					};
					client.DownloadFileAsync(new Uri(this.Latest.FileUrl), dest.FullName);
				}
			}
			catch(WebException exception) {
				if(this.Error != null) {
					this.Error(this, new UnhandledExceptionEventArgs(exception, false));
				}
				this.Status = UpdateStatus.Problem;
			}
		}
Пример #52
0
 public abstract void Download(DownloadProgressChangedEventHandler progressHandler = null,
     AsyncCompletedEventHandler completedHandler = null);
Пример #53
0
 public string DownloadEvent(ICamEvent camEvent, AsyncCompletedEventHandler fileDownloadCompleted, DownloadProgressChangedEventHandler progressChanged)
 {
     return _connector.DownloadEvent(camEvent, fileDownloadCompleted, progressChanged);
 }
 private void CalculateFolderSize(object value)
 {
     Stack<IVirtualFolder> stack = new Stack<IVirtualFolder>();
     stack.Push(this.FOwner);
     Exception error = null;
     Stopwatch stopwatch = new Stopwatch();
     stopwatch.Start();
     try
     {
         while (stack.Count > 0)
         {
             using (IVirtualFolder folder = stack.Pop())
             {
                 foreach (IVirtualItem item in folder.GetContent())
                 {
                     if (item is IVirtualFolder)
                     {
                         stack.Push((IVirtualFolder) item);
                     }
                     else
                     {
                         object obj2 = item[3];
                         if (obj2 != null)
                         {
                             this.Size += (long) obj2;
                         }
                         obj2 = item[5];
                         if (obj2 != null)
                         {
                             this.CompressedSize += Convert.ToInt64(obj2);
                         }
                         if ((this.FOwnerParent != null) && (stopwatch.ElapsedMilliseconds >= 500L))
                         {
                             stopwatch.Reset();
                             this.FOwnerParent.RaiseChanged(WatcherChangeTypes.Changed, this.FOwner);
                             stopwatch.Start();
                         }
                     }
                 }
             }
         }
     }
     catch (Exception exception2)
     {
         error = exception2;
     }
     finally
     {
         stopwatch.Stop();
         if (this.FOwnerParent != null)
         {
             this.FOwnerParent.RaiseChanged(WatcherChangeTypes.Changed, this.FOwner);
         }
         this.FOwner = null;
         this.FOwnerParent = null;
         if (this.FCompleted != null)
         {
             this.FCompleted(this, new AsyncCompletedEventArgs(error, false, null));
             this.FCompleted = null;
         }
     }
 }
Пример #55
0
        /// <summary>
        /// Download a file from the internet and place it in the local documents directory
        /// </summary>
        /// <param name="_filename">The name of the file to download</param>
        private async Task _LoadFile(string _filename, DownloadProgressChangedEventHandler progress, AsyncCompletedEventHandler finished)
        {
            var wc = new WebClient();

            wc.DownloadProgressChanged += progress;
            wc.DownloadFileCompleted += finished;
            try
            {
                _downloading = _files2fetch.Count.ToString() + ": " + _filename + "()";
                await wc.DownloadFileTaskAsync("http://casim.hhu.de/Crawler/" + _filename, ".\\Content\\" + _filename);
            }
            catch
            {
                finished(null, null);
            }
        }
Пример #56
0
        private void GetChangeLogCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (InvokeRequired)
            {
                var myDelegate = new AsyncCompletedEventHandler(GetChangeLogCompleted);
                Invoke(myDelegate, sender, e);
                return;
            }

            try
            {
                _appUpdate.GetChangeLogCompletedEvent -= GetChangeLogCompleted;

                if (e.Cancelled)
                    return;
                if (e.Error != null)
                    throw e.Error;

                txtChangeLog.Text = _appUpdate.ChangeLog.Replace("\n", Environment.NewLine);
            }
            catch (Exception ex)
            {
                Runtime.MessageCollector.AddExceptionMessage(Language.strUpdateGetChangeLogFailed, ex);
            }
        }
Пример #57
0
        public static int DownloadSong(SongInformation inf, AsyncCompletedEventHandler handler)
        {
            if (inf == null || inf.fileName == "" || inf.path == "" || inf.file == "")
                return -1;

            if (!Directory.Exists(inf.path))
            {
                Directory.CreateDirectory(inf.path);
            }
            if (File.Exists(inf.path + "\\" + inf.file))
                return 0;

            WebClient webClient = new WebClient();
            webClient.DownloadFileAsync(new Uri(inf.fileName), inf.path + "\\" + inf.file);
            webClient.DownloadFileCompleted += handler;
            return 1;
        }
Пример #58
0
        // Does not work yet.. does not return at the moment, not sure why, specs seem to be correctly implemented
        //public async Task<string> GetEventStream(CamEvent camEvent)
        //{
        //    var httpRequest = new HttpRequest();
        //    httpRequest.Parameters.Add("api", "SYNO.SurveillanceStation.Streaming");
        //    httpRequest.Parameters.Add("version", "1");
        //    httpRequest.Parameters.Add("_sid", _sessionId);
        //    httpRequest.Parameters.Add("eventId", camEvent.Id.ToString());
        //    httpRequest.Parameters.Add("method", "EventStream");

        //    httpRequest.Headers.Add("User-Agent", "SynoCam");
        //    httpRequest.Headers.Add("Range", "bytes=0-9999999");
        //    httpRequest.Headers.Add("Icy-MetaData", "1");

        //    var eventData = await GetDataFromUrl(httpRequest, _url + "streaming.cgi");

        //    return "";
        //}

        public string DownloadEvent(ICamEvent camEvent, AsyncCompletedEventHandler fileDownloadCompleted, DownloadProgressChangedEventHandler progressChanged)
        {
            string tempPath = Path.GetTempPath();

            string nameWithoutPrefix = camEvent.Name.Substring(camEvent.Name.LastIndexOf("/", StringComparison.Ordinal) + 1);
            string url = string.Format("{0}entry.cgi/{1}?api=SYNO.SurveillanceStation.Event&method=Download&version=4&eventId={2}&_sid={3}", _url, nameWithoutPrefix, camEvent.Id, _sessionId);

            string tempFile = Path.Combine(tempPath, nameWithoutPrefix);

            using (var downloadClient = new WebClient())
            {
                downloadClient.DownloadFileCompleted += fileDownloadCompleted;
                downloadClient.DownloadFileCompleted += (sender, args) => _deleteFilesBeforeExit.Add(tempFile);
                downloadClient.DownloadProgressChanged += progressChanged;
                downloadClient.DownloadFileAsync(new Uri(url), tempFile);
            }

            return tempFile;
        }
Пример #59
0
        public void DownloadInstallerAsync(DownloadProgressChangedEventHandler progress, AsyncCompletedEventHandler completed)
        {
            var client = new WebClient();
            if(progress != null){
                client.DownloadProgressChanged += progress;
            }
            if(completed != null){
                client.DownloadFileCompleted += completed;
            }

            string file = Path.GetTempPath() + Path.GetFileName(this.InstallerUri.AbsolutePath);
            client.DownloadFileAsync(this.InstallerUri, file, file);
        }
Пример #60
0
 public string DownloadEvent(ICamEvent camEvent, AsyncCompletedEventHandler fileDownloadCompleted, DownloadProgressChangedEventHandler progressChanged)
 {
     throw new NotImplementedException();
 }