public void Download(string path, DownloadProgressChangedEventHandler progress, bool async)
 {
     if (FileName == "")
     {
         return;
     }
     using (WebClient client = new WebClient())
     {
         client.DownloadProgressChanged += progress;
         client.DownloadDataCompleted   += (sender, eventargs) =>
         {
             Console.Out.WriteLine("File transfer completed");
         };
         if (async)
         {
             client.DownloadFileAsync(Uri, path + @"\" + FileName);
         }
         else
         {
             client.DownloadFile(Uri, path + @"\" + FileName);
             Thread.Sleep(1000);
             IsValid(path);
         }
     }
 }
Beispiel #2
0
        /// <summary>
        ///     Download Update and apply update (all arguments are FullPath)
        /// </summary>
        /// <param name="downloadDirectory"></param>
        /// <param name="installDirectory"></param>
        /// <param name="onDownloadProgressChanged"></param>
        /// <param name="keyword"></param>
        /// <exception cref="MessageException"></exception>
        public static void DownloadAndUpdate(string downloadDirectory,
                                             string installDirectory,
                                             DownloadProgressChangedEventHandler onDownloadProgressChanged,
                                             string?keyword = null)
        {
            UpdateChecker.GetLatestUpdateFileNameAndHash(out var updateFileName, out var sha256, keyword);

            // update file Full Path
            var updateFile = Path.Combine(downloadDirectory, updateFileName);
            var updater    = new Updater(updateFile, installDirectory);

            if (File.Exists(updateFile))
            {
                if (Utils.Utils.SHA256CheckSum(updateFile) == sha256)
                {
                    updater.ApplyUpdate();
                    return;
                }

                File.Delete(updateFile);
            }

            DownloadUpdateFile(onDownloadProgressChanged, updateFile, sha256);
            updater.ApplyUpdate();
        }
Beispiel #3
0
    public void DownLoad(string url, string fileName, DownloadProgressChangedEventHandler DownLoadListener, CallBack DwonDone)
    {
        this.url      = url;
        this.fileName = fileName;

        WebClient webClient = new WebClient();

        if (url == null)
        {
            if (DwonDone != null)
            {
                this.state = "Final";
                DwonDone(this);
            }
            return;
        }

        url = url.Replace(@"\", @"");
        //if (webClient.IsBusy)
        //{
        //    webClient.CancelAsync();
        //}
        if (DownLoadListener != null)
        {
            this.DownLoadListener = DownLoadListener;
        }
        if (DwonDone != null)
        {
            this.CallBackDone = DwonDone;
        }

        //用于记录
        webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(DownOKorErr);
        webClient.DownloadFileAsync(new Uri(url), fileName);
    }
        /// <summary>
        /// Downloads a specific file.
        /// </summary>
        public async Task DownloadAndExtract(DownloadProgressChangedEventHandler progressChanged)
        {
            // Start the modification download.
            byte[] data;
            using (WebClient client = new WebClient())
            {
                client.DownloadProgressChanged += progressChanged;
                data = await client.DownloadDataTaskAsync(Uri);
            }

            /* Extract to Temp Directory */
            string temporaryDirectory = GetTemporaryDirectory();
            var    archiveExtractor   = new ArchiveExtractor();
            await archiveExtractor.ExtractPackageAsync(data, temporaryDirectory);

            /* Get name of package. */
            var configReader = new ConfigReader <ModConfig>();
            var configs      = configReader.ReadConfigurations(temporaryDirectory, ModConfig.ConfigFileName);
            var loaderConfig = LoaderConfigReader.ReadConfiguration();

            foreach (var config in configs)
            {
                string configId        = config.Object.ModId;
                string configDirectory = Path.GetDirectoryName(config.Path);
                string targetDirectory = Path.Combine(loaderConfig.ModConfigDirectory, configId);
                IOEx.MoveDirectory(configDirectory, targetDirectory);
            }

            Directory.Delete(temporaryDirectory, true);
        }
Beispiel #5
0
 public void DownloadFileAsync(Uri uri, string filePath, DownloadProgressChangedEventHandler progressHandler = null, AsyncCompletedEventHandler completedHandler = null)
 {
     lhLoom.RunAsync(() =>
     {
         using (WebClient client = new WebClient())
         {
             client.DownloadProgressChanged += (sender, e) => {
                 lhLoom.RunMain(() =>
                 {
                     if (progressHandler != null)
                     {
                         progressHandler(sender, e);
                     }
                 });
             };
             client.DownloadFileCompleted += (sender, e) => {
                 lhLoom.RunMain(() =>
                 {
                     if (completedHandler != null)
                     {
                         completedHandler(sender, e);
                     }
                 });
             };
             client.DownloadFileAsync(uri, filePath);
         }
     });
 }
Beispiel #6
0
        /// <summary>
        /// Downloads a byte array to be used programmatically.
        /// </summary>
        /// <param name="supabasePath"></param>
        /// <param name="onProgress"></param>
        /// <returns></returns>
        public Task <byte[]> Download(string supabasePath, DownloadProgressChangedEventHandler onProgress = null)
        {
            var tsc = new TaskCompletionSource <byte[]>();

            try
            {
                WebClient client = new WebClient();
                Uri       uri    = new Uri($"{Url}/object/{GetFinalPath(supabasePath)}");

                foreach (var header in Headers)
                {
                    client.Headers.Add(header.Key, header.Value);
                }

                if (onProgress != null)
                {
                    client.DownloadProgressChanged += onProgress;
                }


                client.DownloadDataCompleted += (sender, args) => tsc.SetResult(args.Result);

                client.DownloadDataAsync(uri);
            }
            catch (Exception ex)
            {
                tsc.SetException(ex);
            }

            return(tsc.Task);
        }
Beispiel #7
0
        public static async Task UpdateToNewVersion(DownloadProgressChangedEventHandler dpceh, System.ComponentModel.AsyncCompletedEventHandler aceh)
        {
            var       downloadPath = Path.GetTempFileName();
            WebClient wc           = new WebClient();

            wc.DownloadProgressChanged += dpceh;
            wc.DownloadFileCompleted   += aceh;
            await wc.DownloadFileTaskAsync(exeUrl, downloadPath);

            //Rename current executable as backup
            try
            {
                //Wait for a second before restarting
                await Task.Delay(1000);

                string exeName = Process.GetCurrentProcess().ProcessName;
                File.Delete(exeName + ".bak");
                File.Move(exeName + ".exe", exeName + ".bak");
                File.Move(downloadPath, exeName + ".exe");

                Process.Start(exeName + ".exe");
                Environment.Exit(0);
            }
            catch (Exception e)
            {
                MessageBox.Show("Unable to replace with updated executable. Check whether the executable is marked as read-only, or whether it is in a protected folder that requires administrative rights.");
            }
        }
        public async Task DownloadBytes()
        {
            var tsc = new TaskCompletionSource <bool>();

            var data     = new Byte[] { 0x0 };
            var name     = $"{Guid.NewGuid()}.bin";
            var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Replace("file:", "");

            await bucket.Upload(data, name);

            DownloadProgressChangedEventHandler onProgress = (sender, args) =>
            {
                tsc.TrySetResult(true);
            };

            var downloadPath = Path.Combine(basePath, name);
            var result       = await bucket.Download(name, onProgress);

            var sentProgressEvent = await tsc.Task;

            Assert.IsTrue(sentProgressEvent);

            Assert.IsTrue(data.SequenceEqual(result));

            await bucket.Remove(new List <string> {
                name
            });
        }
Beispiel #9
0
        public async Task Init(DownloadProgressChangedEventHandler onDownloadProgressChanged = null, Object initOptions = null)
#endif
        {
            YoloVersion v = YoloVersion.YoloV4;

            if (initOptions != null && ((initOptions as String) != null))
            {
                String versionStr = initOptions as String;
                if (versionStr.Equals("YoloV3Spp"))
                {
                    v = YoloVersion.YoloV3Spp;
                }
                else if (versionStr.Equals("YoloV3Tiny"))
                {
                    v = YoloVersion.YoloV3Tiny;
                }
                else if (versionStr.Equals("YoloV3"))
                {
                    v = YoloVersion.YoloV3;
                }
                else if (versionStr.Equals("YoloV4Tiny"))
                {
                    v = YoloVersion.YoloV4Tiny;
                }
            }
#if UNITY_EDITOR || UNITY_IOS || UNITY_ANDROID || UNITY_STANDALONE || UNITY_WEBGL
            yield return(Init(v, onDownloadProgressChanged));
#else
            await Init(v, onDownloadProgressChanged);
#endif
        }
Beispiel #10
0
        public static void DownloadMedia(String conversationID, String fileID, String savePath,
                                         DownloadProgressChangedEventHandler onProgressChange, AsyncCompletedEventHandler onDownloadComplete, ErrorHandler errorHandler, [CallerMemberName] string caller = null)
        {
            String streamUrl = StreamAPI.GetMediaURL(fileID, conversationID);

            DownloadMedia(streamUrl, savePath, onProgressChange, onDownloadComplete, errorHandler, caller);
        }
Beispiel #11
0
        private void DownloadFile(string urlAddress, string location, DownloadProgressChangedEventHandler downloadProgressCallback, AsyncCompletedEventHandler downloadCompleteCallback)
        {
            lastDownloadedFilePath  = location;
            lastDownloadedRemoteUrl = urlAddress;
            using (webClient = new WebClient())
            {
                webClient.DownloadFileCompleted   += new AsyncCompletedEventHandler(downloadCompleteCallback);
                webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloadProgressCallback);

                // The variable that will be holding the url address (making sure it starts with http://)
                Uri URL = urlAddress.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ? new Uri(urlAddress) : new Uri(PatchHost + urlAddress);

                // Start the stopwatch which we will be using to calculate the download speed
                sw.Start();

                try
                {
                    // Start downloading the file
                    webClient.DownloadFileAsync(URL, location);
                }
                catch (Exception ex)
                {
                    StatusLable.Text = ex.Message;
                }
            }
        }
Beispiel #12
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);
            }
        }
Beispiel #13
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);
        }
		/// <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;
		}
Beispiel #15
0
        private Task doDownload(Uri uri, string savePath, DownloadProgressChangedEventHandler progressChangedHandler)
        {
            //如果目录不存在则自动创建
            FileInfo      savePathInfo = new FileInfo(savePath);
            DirectoryInfo saveDir      = savePathInfo.Directory;

            if (!saveDir.Exists)
            {
                saveDir.Create();
            }
            this.downloadComplete = false;
            WebClient client = new WebClient();

            client.DownloadProgressChanged += progressChangedHandler;
            client.DownloadFileCompleted   += new AsyncCompletedEventHandler((object sender, AsyncCompletedEventArgs e) =>
            {
                this.downloadComplete = true;
            });
            client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
            client.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
            return(Task.Run(async() =>
            {
                await client.DownloadFileTaskAsync(uri, savePath);
                while (!this.downloadComplete)
                {
                    //等待下载完成事件触发
                }
            }));
        }
        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);
            }
        }
Beispiel #17
0
 /// <summary>
 /// Download and initialize the DNN face and facemark detector
 /// </summary>
 /// <param name="onDownloadProgressChanged">Callback when download progress has been changed</param>
 /// <returns>Async task</returns>
 public async Task Init(
     DownloadProgressChangedEventHandler onDownloadProgressChanged = null,
     Object initOptions = null)
 {
     await InitFaceDetector(onDownloadProgressChanged);
     await InitFacemark(onDownloadProgressChanged);
 }
Beispiel #18
0
 public void Download(Uri url, string destination, DownloadProgressChangedEventHandler downloadProgress, AsyncCompletedEventHandler downloadCompleted)
 {
     try
     {
         if (Utils.IsInternetAvailable)
         {
             Dispatcher.CurrentDispatcher.InvokeAsync(() =>
             {
                 WebClient webClient = new WebClient();
                 webClient.DownloadProgressChanged += downloadProgress;
                 webClient.DownloadFileCompleted   += downloadCompleted;
                 webClient.DownloadFileAsync(url, destination);
             });
         }
         else
         {
             errorHandler.ShowWarning(Constants.INTERNET_IS_DISABLED_MESSAGE);
             Utils.CloseApp();
         }
     }
     catch (Exception exc)
     {
         errorHandler.ShowError(exc.Message);
     }
 }
		/// <see cref="IAsyncWebClient.DownloadDataAsync"/>
		public Task<byte[]> DownloadDataAsync(Uri address, IProgress<DownloadProgressChangedEventArgs> progress, CancellationToken cancellationToken)
		{
			cancellationToken.Register(() => _webClient.CancelAsync());

			var cookie = Guid.NewGuid();
			var tcs = new TaskCompletionSource<byte[]>();

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

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

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

				tcs.TrySetFromEventArgs(e, args => args.Result);
			};
			_webClient.DownloadDataCompleted += completedHandler;

			_webClient.DownloadDataAsync(address, cookie);
			return tcs.Task;
		}
Beispiel #20
0
        public async Task Download_ShouldBeCancelled_WhenCancelledWhilePaused()
        {
            var downloadSession = await GetTestDownloadSession();

            DownloadProgressChangedEventHandler handler = null;

            handler = async(sender, args) =>
            {
                // Execute this only once
                downloadSession.DownloadProgressChanged -= handler;

                Assert.AreEqual(DownloadState.Downloading, downloadSession.State);

                // Pause download session on the first download progress
                await args.Session.PauseAsync();
            };
            downloadSession.DownloadProgressChanged += handler;
            await downloadSession.DownloadAsync();

            // It should be paused right now
            IsPaused(downloadSession);

            // Wait a couple seconds
            await Task.Delay(TimeSpan.FromSeconds(2));

            // Continue download
            await downloadSession.CancelAsync();

            // then it should be cancelled and both target and partial files should not exist
            IsCancelled(downloadSession);
        }
Beispiel #21
0
        public Task <bool> DownloadUpdate(DownloadProgressChangedEventHandler eventHandler)
        {
            if (File.Exists(UpdateFileLocalPath))
            {
                File.Delete(UpdateFileLocalPath);
            }

            TaskCompletionSource <bool> tcs = new TaskCompletionSource <bool>();

            using (var cli = new WebClient())
            {
                if (eventHandler != null)
                {
                    cli.DownloadProgressChanged += eventHandler;
                    cli.DownloadFileCompleted   += (sender, e) =>
                    {
                        if (e.Cancelled || e.Error != null)
                        {
                            tcs.SetResult(false);
                        }
                        else
                        {
                            tcs.SetResult(true);
                        }
                    };
                }

                cli.DownloadFileTaskAsync(DownloadLink, UpdateFileLocalPath);
            }

            return(tcs.Task);
        }
Beispiel #22
0
        private async Task DownloadFile(String url, String currentID, StreamWriter sw)
        {
            String name = currentID + ".zip";
            DownloadProgressChangedEventHandler DownloadProgressChangedEvent = (s, e) =>
            {
                progressBar1.BeginInvoke((Action)(() =>
                {
                    progressBar1.Value = e.ProgressPercentage;
                }));

                var downloadProgress = string.Format("{0} MB / {1} MB",
                                                     (e.BytesReceived / 1024d / 1024d).ToString("0.00"),
                                                     (e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00"));

                label1.BeginInvoke((Action)(() =>
                {
                    label1.Text = "Loading map: " + currentID + " | " + downloadProgress;
                }));
            };

            using (var client = new WebClient())
            {
                client.DownloadProgressChanged += DownloadProgressChangedEvent;
                await client.DownloadFileTaskAsync(url, name);

                if (File.Exists(name))
                {
                    File.Move(name, zipsPath + name);
                    sw.WriteLine(currentID);
                }
            }
        }
Beispiel #23
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));
            }
        }
 public static Task Start(out WebClient result, string uri, string path, DownloadProgressChangedEventHandler h1, AsyncCompletedEventHandler h2)
 {
     result = GetClient();
     result.DownloadProgressChanged += h1;
     result.DownloadFileCompleted   += h2;
     return(result.DownloadFileTaskAsync(uri, path));
 }
        /// <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)
            };
        }
        private void RelhaxWindow_Closed(object sender, EventArgs e)
        {
            //close windows if open
            loggerDispatcher?.Invoke(() => { if (logViewer.IsLoaded)
                                             {
                                                 logViewer.Close();
                                             }
                                     });

            if (htmlPathSelector != null && htmlPathSelector.IsLoaded)
            {
                htmlPathSelector.Close();
            }

            //disposal
            if (AutomationSequencer != null)
            {
                AutomationSequencer.Dispose();
            }
            if (cancellationTokenSource != null)
            {
                cancellationTokenSource.Dispose();
            }
            DownloadProgressChanged = null;
        }
Beispiel #27
0
        public static UpdateWindow.ErrorState DownloadFile(string url, Uri serverAddress,
                                                           out Stream str, DownloadProgressChangedEventHandler wc_DownloadProgressChanged)
        {
            ensureSensibleCacheFolderExists();
            UpdateWindow.ErrorState er = UpdateWindow.ErrorState.Successful;
            string updateCache         = MeGUISettings.MeGUIUpdateCache;

            string   localFilename = Path.Combine(updateCache, url);
            FileInfo finfo         = new FileInfo(localFilename);

            if (File.Exists(localFilename) && (finfo.Length == 0))
            {
                try
                {
                    finfo.Delete();
                }
                catch (IOException) { }
            }
            else if (File.Exists(localFilename))
            {
                goto gotLocalFile;
            }

            WebClient        wc  = new WebClient();
            ManualResetEvent mre = new ManualResetEvent(false);

            wc.DownloadFileCompleted += delegate(object sender, AsyncCompletedEventArgs e)
            {
                if (e.Error != null)
                {
                    er = UpdateWindow.ErrorState.CouldNotDownloadFile;
                }

                mre.Set();
            };

            wc.DownloadProgressChanged += wc_DownloadProgressChanged;

            wc.DownloadFileAsync(new Uri(serverAddress, url), localFilename);
            mre.WaitOne();

gotLocalFile:
            try
            {
                File.SetLastWriteTime(localFilename, DateTime.Now);
            }
            catch (IOException) { }

            try
            {
                str = File.OpenRead(localFilename);
            }
            catch (IOException)
            {
                str = null;
                return(UpdateWindow.ErrorState.CouldNotDownloadFile);
            }

            return(er);
        }
Beispiel #28
0
        public static void DownloadAndUpdate(string downloadPath,
                                             string targetPath,
                                             DownloadProgressChangedEventHandler onDownloadProgressChanged,
                                             string?keyword = null)
        {
            if (!UpdateChecker.GetFileNameAndHashFromMarkdownForm(UpdateChecker.LatestRelease.body, out var fileName, out var sha256, keyword))
            {
                throw new MessageException(i18N.Translate("parse release note failed"));
            }

            var fileFullPath = Path.Combine(downloadPath, fileName);
            var updater      = new Updater(fileFullPath, targetPath);

            if (File.Exists(fileFullPath))
            {
                if (Utils.Utils.SHA256CheckSum(fileFullPath) == sha256)
                {
                    updater.ApplyUpdate();
                    return;
                }

                File.Delete(fileFullPath);
            }

            DownloadUpdate(onDownloadProgressChanged, fileFullPath, sha256);
            updater.ApplyUpdate();
        }
        public async Task DownloadContent(Guid id, string destPath, DownloadProgressChangedEventHandler handler)
        {
            client.DownloadProgressChanged += handler;
            await client.DownloadFileTaskAsync($"https://store.{server}/sites/default/files/{id.ToString("D").ToUpperInvariant()}.zip", destPath);

            client.DownloadProgressChanged -= handler;
        }
        public void Download(string version, DownloadProgressChangedEventHandler method)
        {
            CreateVersionDirectory(version);

            var llvmUri        = new LlvmUri();
            var executablePath = settingsPathBuilder.GetLlvmExecutablePath(version, LlvmConstants.Llvm + version);
            var uri            = string.Empty;

            if (version == versionAlternateUri)
            {
                uri = llvmUri.GetGitHubUri(version);
            }
            else
            {
                uri = llvmUri.GetDefaultUri(version);
            }


            try
            {
                using (var client = new WebClient())
                {
                    client.DownloadProgressChanged += method;
                    client.DownloadFileCompleted   += DownloadCompleted;
                    downloadCancellationToken.Token.Register(client.CancelAsync);
                    client.DownloadFileAsync(new Uri(uri), executablePath);
                }
            }
            catch (Exception)
            {
                DownloadCanceled();
            }
        }
Beispiel #31
0
        /// <summary>
        /// Синхронная или асинхронная загрузка данных
        /// </summary>
        /// <param name="url">Адрес</param>
        /// <param name="progress">Обработчик события прогресса загрузки для асинхронной загрузки (null для синхронной</param>
        /// <param name="complete">Обработчик события завершения загрузки</param>
        /// <returns>Результат синхронной загрузки или null при неудаче, всегда null при асинхронной</returns>
        public static string DownloadPageSilent(string url, DownloadProgressChangedEventHandler progress,
                                                DownloadDataCompletedEventHandler complete)
        {
            byte[] buffer = null;
            int tries = 0;

            var client = new WebClient();
            try
            {
                if (_proxySetting.UseProxy)
                {
                    IPAddress test;
                    if (!IPAddress.TryParse(_proxySetting.Address, out test))
                        throw new ArgumentException("Некорректный адрес прокси сервера");
                    client.Proxy = _proxySetting.UseAuthentification
                                       ? new WebProxy(
                                             new Uri("http://" + _proxySetting.Address + ":" + _proxySetting.Port),
                                             false,
                                             new string[0],
                                             new NetworkCredential(_proxySetting.UserName, _proxySetting.Password))
                                       : new WebProxy(
                                             new Uri("http://" + _proxySetting.Address + ":" + _proxySetting.Port));
                }
            }
            catch (Exception ex)
            {
                _logger.Add(ex.StackTrace, false, true);
                _logger.Add(ex.Message, false, true);
                _logger.Add("Ошибка конструктора прокси", false, true);
            }

            while (tries < 3)
            {
                try
                {
                    SetHttpHeaders(client, null);
                    if (progress == null)
                        buffer = client.DownloadData(url);
                    else
                    {
                        client.DownloadProgressChanged += progress;
                        client.DownloadDataCompleted += complete;
                        client.DownloadDataAsync(new Uri(url));
                        return null;
                    }
                    break;
                }
                catch (Exception ex)
                {
                    _logger.Add(ex.StackTrace, false, true);
                    _logger.Add(ex.Message, false, true);
                    _logger.Add("Ошибка загрузки страницы", false, true);
                    tries++;
                }
            }

            return (buffer != null) ? ConvertPage(buffer) : null;
        }
        public void DownloadModAsync(ModDatabaseMod mod, Action<byte[]> callback, DownloadProgressChangedEventHandler progressChanged = null )
        {
            var url = new Uri(ModDatabaseUrl, mod.DownloadLink);
            var client = CreateClient();

            client.DownloadDataCompleted += (o, e) => callback(e.Result);
            client.DownloadProgressChanged += progressChanged;

            client.DownloadDataAsync(url);
        }
Beispiel #33
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);
        }
 /// <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));
 }
 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();
   }
 }
    /// <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);
    }
Beispiel #38
0
        /// <summary>
        /// 下載指定檔案
        /// </summary>
        public static void DownloadFileAsync(
            string address,
            string fileName,
            DownloadProgressChangedEventHandler DownloadProgressChanged,
            System.ComponentModel.AsyncCompletedEventHandler DownloadFileCompleted)
        {
            WebClient Client = new WebClient();

            if (DownloadProgressChanged != null)
                Client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressChanged);

            if (DownloadFileCompleted != null)
                Client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(DownloadFileCompleted);

            Uri url = new Uri(address);
            Client.DownloadFileAsync(url, fileName);
        }
 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;
 }
Beispiel #40
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);
   }
 }
Beispiel #42
0
 public void SetDownloadXMLProgressChanged(DownloadProgressChangedEventHandler value)
 {
     this.downloadFileProgressChanged = new DownloadProgressChangedEventHandler(value);
 }
Beispiel #43
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);
        }
Beispiel #44
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);
            }
        }
Beispiel #45
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);
                }
            }
        /// <summary>
        /// Downloads a mod from KSP Spaceport.
        /// </summary>
        /// <param name="modInfo"></param>
        /// <returns></returns>
        public static bool DownloadMod(string downloadURL, ref ModInfo modInfo, DownloadProgressChangedEventHandler downloadProgressHandler = null)
        {
            if (modInfo == null || string.IsNullOrEmpty(downloadURL))
                return false;

            // get save path 
            string filename = downloadURL;
            int start = filename.LastIndexOf("?");
            if (start > -1)
            {
                string filenameA = filename.Substring(0, start);
                string filenameB = filename.Substring(start + 1);
                Regex regEx = new Regex("[.](zip)|(rar)|(7zip)");
                if (regEx.IsMatch(filenameA))
                    filename = filenameA;
                else if (regEx.IsMatch(filenameB))
                    filename = filenameB;
                else
                    return false;
            }
            start = filename.LastIndexOf("/") + 1;
            filename = filename.Substring(start, filename.Length - start);
            modInfo.LocalPath = Path.Combine(OptionsController.DownloadPath, filename);
            www.DownloadFile(downloadURL, modInfo.LocalPath, downloadProgressHandler);

            return true;
        }
Beispiel #47
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);
            }
        }
 public abstract void Download(DownloadProgressChangedEventHandler progressHandler = null,
     AsyncCompletedEventHandler completedHandler = null);
Beispiel #49
0
 public void Download(String fileurl, String filename, System.ComponentModel.AsyncCompletedEventHandler onComplete, DownloadProgressChangedEventHandler onProgress)
 {
     var wc = new System.Net.WebClient();
     wc.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(onComplete);
     wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(onProgress);
     var furi = new Uri(fileurl);
     wc.DownloadFileAsync(furi, filename);
 }
 private void FileDownload_Load(object sender, EventArgs e)
 {
     ProgressChanged += new DownloadProgressChangedEventHandler(FileDownload_ProgressChanged);
     DownloadComplete += new AsyncCompletedEventHandler(FileDownload_DownloadComplete);
 }
        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);
            }
        }
 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;
 }
 /// <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)
     {
     }
 }
Beispiel #54
0
        public static UpdateWindow.ErrorState DownloadFile(string url, Uri serverAddress,
            out Stream str, DownloadProgressChangedEventHandler wc_DownloadProgressChanged)
        {
            ensureSensibleCacheFolderExists();
            UpdateWindow.ErrorState er = UpdateWindow.ErrorState.Successful;
            string updateCache = MainForm.Instance.Settings.MeGUIUpdateCache;

            string localFilename = Path.Combine(updateCache, url);
            FileInfo finfo = new FileInfo(localFilename);
            if (File.Exists(localFilename) && (finfo.Length == 0))
            {
                try
                {
                    finfo.Delete();
                }
                catch (IOException) { }
            }
            else if (File.Exists(localFilename))
            {
                // check the zip file
                if (localFilename.ToLower().EndsWith(".zip"))
                {
                    try
                    {
                        ZipFile zipFile = new ZipFile(localFilename);
                        if (zipFile.TestArchive(true) == false)
                        {
                            try
                            {
                                finfo.Delete();
                            }
                            catch (IOException) { }
                        }
                        else
                        {
                            goto gotLocalFile;
                        }
                    }
                    catch
                    {
                        try
                        {
                            finfo.Delete();
                        }
                        catch (IOException) { }
                    }
                }
                else
                {
                    goto gotLocalFile;
                }
            }

            WebClient wc = new WebClient();

            // check for proxy authentication...
            if (MainForm.Instance.Settings.UseHttpProxy == true)
            {
                WebProxy wprox = null;
                ICredentials icred = null;

                if (MainForm.Instance.Settings.HttpProxyUid != null)
                {
                    icred = new NetworkCredential(MainForm.Instance.Settings.HttpProxyUid, MainForm.Instance.Settings.HttpProxyPwd);
                }

                wprox = new WebProxy(MainForm.Instance.Settings.HttpProxyAddress + ":" + MainForm.Instance.Settings.HttpProxyPort, true, null, icred);

                WebRequest.DefaultWebProxy = wprox;
                wc.Proxy = wprox;
            }
            else
            {
                wc.Proxy = null;
            }

            ManualResetEvent mre = new ManualResetEvent(false);
            wc.DownloadFileCompleted += delegate(object sender, AsyncCompletedEventArgs e)
            {
                if (e.Error != null)
                    er = UpdateWindow.ErrorState.CouldNotDownloadFile;

                mre.Set();
            };

            wc.DownloadProgressChanged += wc_DownloadProgressChanged;

            wc.DownloadFileAsync(new Uri(serverAddress, url), localFilename);
            mre.WaitOne();

            gotLocalFile:
            try
            {
                str = File.OpenRead(localFilename);
            }
            catch (IOException)
            {
                str = null;
                return UpdateWindow.ErrorState.CouldNotDownloadFile;
            }

            return er;
        }
Beispiel #55
0
        //public delegate void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e);
        public static void DownloadFile(string source, string destination, DownloadProgressChangedEventHandler client_DownloadProgressChanged)
        {
            try
            {
                using (WebClient _WebClient = new WebClient())
                {
                    // Downloads the resource with the specified URI
                    // to a local file.
                    _WebClient.DownloadProgressChanged += client_DownloadProgressChanged;

                    Uri remoteUri = new Uri(source);
                    destination = Path.GetFileName(remoteUri.LocalPath);
                    _WebClient.DownloadFileAsync(remoteUri, destination);
                }
            }
            catch (Exception _Exception)
            {
                // Error
                Console.WriteLine("Exception caught in process: {0}",
                    _Exception.ToString());
            }
        }
Beispiel #56
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;
        }
Beispiel #57
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);
        }
 /// <summary>
 /// Downloads a file.
 /// </summary>
 /// <param name="downloadURL">Url to the file to download.</param>
 /// <param name="downloadPath">Path to save the file to.</param>
 /// <param name="downloadProgressHandler"></param>
 public static void DownloadFile(string downloadURL, string downloadPath, DownloadProgressChangedEventHandler downloadProgressHandler = null)
 {
     WebClient webClient = new WebClient();
     webClient.Credentials = CredentialCache.DefaultCredentials;
     webClient.DownloadFile(new Uri(downloadURL), downloadPath);
     if (downloadProgressHandler != null)
         webClient.DownloadProgressChanged += downloadProgressHandler;
 }
Beispiel #59
0
 public string DownloadEvent(ICamEvent camEvent, AsyncCompletedEventHandler fileDownloadCompleted, DownloadProgressChangedEventHandler progressChanged)
 {
     return _connector.DownloadEvent(camEvent, fileDownloadCompleted, progressChanged);
 }
Beispiel #60
0
        /// <summary>
        /// Called when [open read completed].
        /// </summary>
        /// <param name="webClient">The web client.</param>
        /// <param name="tcs">The TCS.</param>
        /// <param name="e">The <see cref="OpenReadCompletedEventArgs"/> instance containing the event data.</param>
        /// <param name="openReadCompletedHandler">The open read completed handler.</param>
        /// <param name="downloadProgressChangedHandler">The download progress changed handler.</param>
        private static void OnOpenReadCompleted(
            WebClient webClient,
            TaskCompletionSource<Stream> tcs,
            OpenReadCompletedEventArgs e,
            OpenReadCompletedEventHandler openReadCompletedHandler,
            DownloadProgressChangedEventHandler downloadProgressChangedHandler)
        {
            if (e.UserState != tcs)
                return;

            try
            {
                if (openReadCompletedHandler != null)
                    webClient.OpenReadCompleted -= openReadCompletedHandler;

                if (downloadProgressChangedHandler != null)
                    webClient.DownloadProgressChanged -= downloadProgressChangedHandler;
            }
            finally
            {
                if (e.Error != null)
                    tcs.TrySetException(e.Error);
                else if (e.Cancelled)
                    tcs.TrySetCanceled();
                else
                    tcs.TrySetResult(e.Result);
            }
        }