public static void GetHighScores() { highScores.Clear(); try { #if UNITY_WEBPLAYER WWW site = new WWW(_leaderboardUrl); while (!site.isDone) { } string jsonScores = site.text; #else WebClient webClient = new WebClient(); webClient.DownloadDataCompleted += HandleDownloadDataCompleted; webClient.Headers.Add("Content-Type", "application/json"); webClient.DownloadDataAsync(_leaderboardUri); #endif } catch(System.Exception ex) { Debug.Log(ex.Message); } }
public static void DownloadDataAsync(this Uri uri, Action<byte[]> action) { if (uri == null) return; WebClient client = new WebClient(); client.DownloadDataAsync(uri); client.DownloadDataCompleted += (sender, e) => { action(e.Result); }; }
public void PokeClients() { TazehaContext context = new TazehaContext(); var nowUTCHour = DateTime.Now.NowHour(); var durations = context.UpdateDurations.Where(x => x.IsLocalyUpdate.Value == false && x.EnabledForUpdate == true && !(nowUTCHour > x.StartSleepTimeHour && nowUTCHour < x.EndSleepTimeHour)); foreach (var duration in durations) { var ServiceLink = duration.ServiceLink; if (!string.IsNullOrEmpty(ServiceLink)) { GeneralLogs.WriteLog("Poke Client " + ServiceLink, TypeOfLog.Start); WebClient client = new WebClient(); client.DownloadDataAsync(new Uri(ServiceLink + "Updater?DurationCode=" + duration.Code.Trim())); GeneralLogs.WriteLog("Poke Client", TypeOfLog.OK); } System.Threading.Thread.Sleep(1000 * 60 * 2); } }
public static void UpdatePACFromGeosite(Configuration config) { string geositeUrl = GEOSITE_URL; string group = config.geositeGroup; bool blacklist = config.geositeBlacklistMode; if (!string.IsNullOrWhiteSpace(config.geositeUrl)) { logger.Info("Found custom Geosite URL in config file"); geositeUrl = config.geositeUrl; } logger.Info($"Checking Geosite from {geositeUrl}"); WebClient http = new WebClient(); if (config.enabled) { http.Proxy = new WebProxy( config.isIPv6Enabled ? $"[{IPAddress.IPv6Loopback}]" : IPAddress.Loopback.ToString(), config.localPort); } http.DownloadDataCompleted += (o, e) => { try { File.WriteAllBytes(DATABASE_PATH, e.Result); LoadGeositeList(); bool pacFileChanged = MergeAndWritePACFile(group, blacklist); UpdateCompleted?.Invoke(null, new GeositeResultEventArgs(pacFileChanged)); } catch (Exception ex) { Error?.Invoke(null, new ErrorEventArgs(ex)); } }; http.DownloadDataAsync(new Uri(geositeUrl)); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); RequestWindowFeature(WindowFeatures.NoTitle); SetContentView(Resource.Layout.Main2); //Load custom font Typeface tf = Typeface.CreateFromAsset(Assets, "transformersmovie.ttf"); TextView titleText = FindViewById <TextView>(Resource.Id.TitleTextView); //Set font of Autospots label in top left corner titleText.SetTypeface(tf, TypefaceStyle.Normal); TextView parkMeTitleText = FindViewById <TextView>(Resource.Id.ParkMeTitleTextView); //Set font of Title text parkMeTitleText.SetTypeface(tf, TypefaceStyle.Normal); mClient1 = new WebClient(); //Download an ID from the server mClient1.DownloadDataAsync(new Uri("http://jamesljenk.pythonanywhere.com/getid/")); mClient1.DownloadDataCompleted += MClient_DownloadIdDataCompleted; //Assign the status text to a variable so it can be changed later statusText = FindViewById <TextView>(Resource.Id.ParkingStatusTextView); //Figure out which lot we're parking in lotIndex = Intent.GetIntExtra("lotIndex", -1); //If the user hasn't chosen a lot to park in... if (lotIndex == -1) { //Display error text statusText.Text = "You have not chosen a default lot. Please go back to the main menu and select \"Find spot in specific lot\" option or specify a default lot in the Preferences menu."; } //Parking lot has been chosen else { spotReceived = false; //Initialize web client used to download location coordinates mclient = new WebClient(); //Start Location services InitializeLocationManager(); } }
public override void Download() { if (_URI != string.Empty) { using (_downloader = new WebClient()) { AddHandlers(); try { _downloader.DownloadDataAsync(new Uri(_URI, UriKind.Absolute)); } catch (Exception) { if (DownloadDataCompleted != null) { DownloadDataCompleted(this, null); } } } } }
public static void GetLatest(Release release) { if (release != null) { Console.WriteLine("UPDATING MOD MANAGER! --- PLEASE WAIT FOR THE UPDATE TO COMPLETE!"); var downloadURL = release.Assets.First().BrowserDownloadUrl; string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads", release.Assets.First().Name); using (var client = new WebClient()) { client.DownloadDataCompleted += (s, e) => { File.WriteAllBytes(fileName, e.Result); Process.Start(fileName); release = null; Environment.Exit(0); }; client.DownloadProgressChanged += (s, e) => { Console.Write($"Downloading version {release.TagName}: {e.ProgressPercentage}%"); }; client.DownloadDataAsync(new Uri(downloadURL)); } } }
private static void OnCommandBinaries(CommandArguments command) { string cdn = "http://media.steampowered.com/client/"; using (var webClient = new WebClient()) { webClient.DownloadDataCompleted += delegate(object sender, DownloadDataCompletedEventArgs e) { var kv = new KeyValue(); using (var ms = new MemoryStream(e.Result)) { try { kv.ReadAsText(ms); } catch { ReplyToCommand(command, "{0}{1}{2}: Something went horribly wrong and keyvalue parser died.", Colors.OLIVE, command.Nickname, Colors.NORMAL); return; } } if (kv["bins_osx"].Children.Count == 0) { ReplyToCommand(command, "{0}{1}{2}: Failed to find binaries in parsed response.", Colors.OLIVE, command.Nickname, Colors.NORMAL); return; } kv = kv["bins_osx"]; ReplyToCommand(command, "{0}{1}{2}:{3} {4}{5} {6}({7} MB)", Colors.OLIVE, command.Nickname, Colors.NORMAL, Colors.DARK_BLUE, cdn, kv["file"].AsString(), Colors.DARK_GRAY, (kv["size"].AsLong() / 1048576.0).ToString("0.###")); }; webClient.DownloadDataAsync(new Uri(string.Format("{0}steam_client_publicbeta_osx?_={1}", cdn, DateTime.UtcNow.Ticks))); } }
public Stream OpenDataFileDirect(byte[] key) { if (worker != null) { worker.ThrowOnCancel(); //worker.ReportProgress(0); } var file = key.ToHexString().ToLower(); var url = CASCConfig.CDNUrl + "/data/" + file.Substring(0, 2) + "/" + file.Substring(2, 2) + "/" + file; WebClient client = new WebClient(); client.DownloadProgressChanged += Client_DownloadProgressChanged; client.DownloadDataCompleted += Client_DownloadDataCompleted; UserState state = new UserState(); client.DownloadDataAsync(new Uri(url), state); state.ResetEvent.WaitOne(); return(state.Stream); }
public CertificateQueryResult Query(ECPoint publickey) { if (!this.initialized) { throw new Exception("Service has not been initialized!"); } var hash = GetRedeemScriptHashFromPublicKey(publickey); lock (results) { if (results.ContainsKey(hash)) { return(results[hash]); } results[hash] = new CertificateQueryResult { Type = CertificateQueryResultType.Querying }; } var path = this.GetCachedCertificatePathFromScriptHash(hash); var address = Wallet.ToAddress(hash); if (this.fileManager.FileExists(path)) { lock (results) { UpdateResultFromFile(hash); } } else { var url = $"http://cert.onchain.com/antshares/{address}.cer"; var web = new WebClient(); web.DownloadDataCompleted += this.Web_DownloadDataCompleted; web.DownloadDataAsync(new Uri(url), hash); } return(results[hash]); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here //SetContentView(Resource.Layout.pager_media_detail); SetContentView(Resource.Layout.pager_default_button_scroll); mVideos = null; mAdapter = null; mProgressBar = FindViewById <ProgressBar>(Resource.Id.progressBar); mListView = FindViewById <ListView>(Resource.Id.listView); mClient = new WebClient(); mUrl = new Uri("http://www.cotykovach.com/GetVideos.php"); //Call php file mClient.DownloadDataAsync(mUrl); mClient.DownloadDataCompleted += mClient_DownloadDataCompleted; }
//获取 private void GetDownloadLinks() { if (NetHelper.IsOnLine()) { ShowMessage(FindResource("网络连接成功").ToString()); using (WebClient wc = new WebClient()) { //获取或设置用于向Internet资源的请求进行身份验证的网络凭据 wc.Credentials = CredentialCache.DefaultCredentials; wc.DownloadDataCompleted += new DownloadDataCompletedEventHandler(DownloadDataCompleted); wc.DownloadDataAsync(new Uri(AppInfo.WikiPage)); ShowMessage("正在获取最新版本信息"); } } else { ShowMessage("未连接网络"); ShowMessage(FindResource("网络连接失败").ToString()); return; } }
public virtual void FireRequest(Action <object, AsyncCompletedEventArgs> callback = null) { emitted = DateTime.Now; try { using (client = new WebClient()) { if (callback != null) { client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(callback); } foreach (DictionaryEntry entry in headers) { client.Headers.Add(entry.Key.ToString(), entry.Value.ToString()); } client.Headers.Add("Keep-Alive", "timeout=15, max=100"); state = RequestStatus.ePending; client.DownloadDataAsync(uri, this); } } catch (Exception ex) { Debug.Log(ForgeLoader.GetCurrentMethod() + " " + ex.Message); state = RequestStatus.eError; } }
public ToolStoreItem(string name, string authors, string organization, string provider, string version, string description, string identifier, string languages, string iconUrl, string downloadUrl) { Name = name; Authors = authors; Organization = organization; Provider = provider; Version = version; Description = description != null?description.Replace("\n", Environment.NewLine) : null; // Not L10N Identifier = identifier; Languages = languages; ToolImage = ToolStoreUtil.DefaultImage; if (iconUrl != null) { IconDownloading = true; var iconUri = new Uri(WebToolStoreClient.TOOL_STORE_URI + iconUrl); var webClient = new WebClient(); webClient.DownloadDataCompleted += DownloadIconDone; webClient.DownloadDataAsync(iconUri); } Installed = ToolStoreUtil.IsInstalled(identifier); IsMostRecentVersion = ToolStoreUtil.IsMostRecentVersion(identifier, version); UriBuilder uri = new UriBuilder(WebToolStoreClient.TOOL_STORE_URI) { Path = WebToolStoreClient.TOOL_DETAILS_URL, Query = "name=" + Uri.EscapeDataString(name) // Not L10N }; FilePath = uri.Uri.AbsoluteUri; // Not L10N }
static Task <AvailableVersionInfo> GetLatestVersionAsync() { var tcs = new TaskCompletionSource <AvailableVersionInfo>(); new Action(() => { WebClient wc = new WebClient(); IWebProxy systemWebProxy = WebRequest.GetSystemWebProxy(); systemWebProxy.Credentials = CredentialCache.DefaultCredentials; wc.Proxy = systemWebProxy; wc.DownloadDataCompleted += delegate(object sender, DownloadDataCompletedEventArgs e) { if (e.Error != null) { tcs.SetException(e.Error); } else { try { XDocument doc = XDocument.Load(new MemoryStream(e.Result)); var bands = doc.Root.Elements("band"); var currentBand = bands.FirstOrDefault(b => (string)b.Attribute("id") == band) ?? bands.First(); Version version = new Version((string)currentBand.Element("latestVersion")); string url = (string)currentBand.Element("downloadUrl"); if (!(url.StartsWith("http://", StringComparison.Ordinal) || url.StartsWith("https://", StringComparison.Ordinal))) { url = null; // don't accept non-urls } latestAvailableVersion = new AvailableVersionInfo { Version = version, DownloadUrl = url }; tcs.SetResult(latestAvailableVersion); } catch (Exception ex) { tcs.SetException(ex); } } }; wc.DownloadDataAsync(UpdateUrl); }).BeginInvoke(null, null); return(tcs.Task); }
/// <summary> /// Custom renderer for SVG images in the markdown as not supported natively. /// @see https://htmlrenderer.codeplex.com/wikipage?title=Rendering%20SVG%20images /// </summary> /// <param name="sender"></param> /// <param name="imageLoadEvent"></param> protected void OnImageLoad(object sender, HtmlImageLoadEventArgs imageLoadEvent) { try { //Get some file information string src = imageLoadEvent.Src; Uri uri = new Uri(src); string extension = Path.GetExtension(src); //Check if local file or web resource switch (uri.Scheme.ToLowerInvariant()) { case "file": //In case of a local file -> Try to load it directly imageLoadEvent.Handled = true; //Tell the event it was handled, so no error border is drawn ThreadPool.QueueUserWorkItem(state => LoadImageFromFile(src, imageLoadEvent)); break; case "http": case "https": //For web resources check extension and parameter, to fetch from e.g. "badge" creating sources if ((extension != null && extension.Equals(".svg", StringComparison.OrdinalIgnoreCase)) || uri.ToString().Contains("svg=")) { //In case of a web resource file -> Load async using (WebClient webClient = new WebClient()) { imageLoadEvent.Handled = true; //Tell the event it was handled, so no error border is drawn webClient.DownloadDataCompleted += (downloadSender, downloadEvent) => { OnDownloadDataCompleted(downloadEvent, imageLoadEvent); }; webClient.DownloadDataAsync(uri); } } break; } } catch { } }
public static void Run() { var wc = new WebClient(); wc.DownloadDataCompleted += (sender, args) => { if (args.Cancelled) { Program.WriteLine("Canceled"); } else if (args.Error != null) { Program.WriteLine("Exception: {0}", args.Error.Message); } else { Program.WriteLine("{0} chars downloaded", args.Result.Length); } }; wc.DownloadDataAsync(new Uri("http://alex-nl.azurewebsites.net/")); Thread.Sleep(1000); }
public override void StartDownload(Uri tileUri, TileInfo tileInfo) { if (TileCache != null) { byte[] bytes = TileCache.Read(tileInfo); if (bytes != null) { tileInfo.Content = bytes; // raise the event this.OnTileDownloadComplete(new TileInfoEventArgs(tileInfo)); return; } } lock (this.webClientsPoolLockObject) { if (!this.webClientsPool.ContainsKey(tileInfo.Id)) { WebClient webClient = new WebClient(); if (Credentials != null) { webClient.Credentials = Credentials; } if (WebProxy != null) { webClient.Proxy = WebProxy; } this.webClientsPool.Add(tileInfo.Id, webClient); this.webRequestCache.Add(tileInfo.Id, tileUri); ImageTileDownloader imageTileDownloader = this; webClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(imageTileDownloader.DownloadTileDataCompleted); webClient.DownloadDataAsync(tileUri, tileInfo); } } }
protected override void Start() { var files = new string[] { "https://github.com/Mpdreamz/shellprogressbar/archive/4.3.0.zip", "https://github.com/Mpdreamz/shellprogressbar/archive/4.2.0.zip", "https://github.com/Mpdreamz/shellprogressbar/archive/4.1.0.zip", "https://github.com/Mpdreamz/shellprogressbar/archive/4.0.0.zip", }; var childOptions = new ProgressBarOptions { ForegroundColor = ConsoleColor.Yellow, ProgressCharacter = '\u2593' }; using var pbar = new ProgressBar(files.Length, "downloading"); foreach (var(file, i) in files.Select((f, i) => (f, i))) { byte[] data = null; using var child = pbar.Spawn(100, "page: " + i, childOptions); try { using var client = new WebClient(); client.DownloadProgressChanged += (o, args) => child.Tick(args.ProgressPercentage); client.DownloadDataCompleted += (o, args) => data = args.Result; client.DownloadDataAsync(new Uri(file)); while (client.IsBusy) { Thread.Sleep(1); } pbar.Tick(); } catch (WebException error) { pbar.WriteLine(error.Message); } } }
/// <summary> /// Downloads the data. /// </summary> /// <param name="url">The URL.</param> /// <param name="httpMethod">The HTTP method.</param> /// <param name="requestData">The request data.</param> /// <param name="callback">The callback.</param> /// <param name="userState">State of the user.</param> /// <returns></returns> /// <remarks></remarks> public static AsyncResult DownloadDataAsync(Uri url, HttpMethod httpMethod, byte[] requestData, AsyncDataCallback callback, object userState) { var web = new WebClient(); web.UploadDataCompleted += WebUploadDataCompleted; web.DownloadDataCompleted += WebDownloadDataCompleted; var wrap = new Wrap(callback, userState); web.Headers.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; BOIE9;ZHCN)"); if (httpMethod == HttpMethod.POST) { web.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); web.UploadDataAsync(url, "POST", requestData, wrap); } else { web.DownloadDataAsync(url, wrap); } return(new AsyncResult(web)); }
public static byte[] smethod_8(string string_0) { // ISSUE: object of a compiler-generated type is created // ISSUE: variable of a compiler-generated type GClass27.Class40 class40 = new GClass27.Class40(); // ISSUE: reference to a compiler-generated field class40.frmWait_0 = new FrmWait("Please wait while USB Helper fetches additional data.", true); WebClient webClient = new WebClient(); // ISSUE: reference to a compiler-generated field class40.byte_0 = (byte[])null; // ISSUE: reference to a compiler-generated method webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(class40.method_0); // ISSUE: reference to a compiler-generated method webClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(class40.method_1); webClient.DownloadDataAsync(new Uri(string_0)); // ISSUE: reference to a compiler-generated field int num = (int)class40.frmWait_0.ShowDialog(); // ISSUE: reference to a compiler-generated field return(class40.byte_0); }
public void AddCredit(string name) { try { name = "https://www.unknowncheats.me/forum/members/" + name + ".html"; var client = new WebClient(); client.DownloadStringCompleted += (sender, args) => { var doc = new HtmlDocument(); doc.LoadHtml(args.Result); var picElement = doc.GetElementbyId("user_avatar"); var imageUrl = picElement.GetAttributeValue("src", ""); var nameElement = doc.GetElementbyId("username_box"); var username = nameElement.ChildNodes[3].FirstChild.InnerText; var imageClient = new WebClient(); imageClient.DownloadDataCompleted += (o, eventArgs) => { var bmp = getThumb(GetImageFromByteArray(eventArgs.Result)); _imageList.Images.Add(username, bmp); _imageList.ImageSize = new Size(96, 96); _imageList.ColorDepth = ColorDepth.Depth32Bit; LargeImageList = _imageList; var listviewItem = new ListViewItem { Text = username, Name = name, ImageIndex = _imageList.Images.Count - 1 }; Items.Add(listviewItem); }; imageClient.Headers.Add("user-agent", "Test"); imageClient.DownloadDataAsync(new Uri(imageUrl)); }; client.Headers.Add("user-agent", "Test"); client.DownloadStringAsync(new Uri(name)); } catch (Exception) { } }
public static async Task <byte[]> DownloadDataAsync(string url, ProgressData progress = null, CancellationToken cancellationToken = default(CancellationToken)) { try { byte[] bytes = null; using (var wc = new WebClient()) { wc.DownloadProgressChanged += (s, e) => progress?.Report(e.BytesReceived, e.TotalBytesToReceive); wc.DownloadDataCompleted += (s, e) => { if (e.Error != null || e.Cancelled) { bytes = null; } bytes = e.Result; }; wc.DownloadDataAsync(new Uri(url)); while (wc.IsBusy) { if (cancellationToken.IsCancellationRequested) { throw new TaskCanceledException("Operation canceled by user."); } await Task.Delay(500); } } return(bytes); } catch { return(null); } }
static void Main(string[] args) { //PrintDisclaimer(); // Create web client using (WebClient client = new WebClient()) { // Set user agent. client.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko"; //"Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " + //"(compatible; MSIE 6.0; Windows NT 5.1; " + //".NET CLR 1.1.4322; .NET CLR 2.0.50727)"; // Accept-encoding headers. client.Headers["Accept-Encoding"] = "html"; client.Headers["Accept-Encoding"] = "text"; // Download data. byte[] arr = client.DownloadData("http://blog.mosinu.com/"); string sTr = client.DownloadString("http://blog.mosinu.com/"); // Get response header. string contentEncoding = client.ResponseHeaders["Content-Encoding"]; // Write values. //Console.WriteLine("--- WebClient result ---"); PrintRedAttentionText(" *** Ferret result *** "); foreach (LinkItem i in LinkFinder.Find(sTr)) { Console.WriteLine(arr.Length); client.DownloadDataAsync(i); //Debug.WriteLine(i); Console.WriteLine(i); } Console.ReadLine(); } }
private void DownloadAndUpdate(string url) { UpdateStatus("downloading new program version", 0); var wc = new WebClient(); wc.Proxy = null; var address = new Uri(UpdateChecker.UpdateCheckHost + url); wc.DownloadProgressChanged += (sender, args) => BeginInvoke((Action) delegate { UpdateStatus(string.Format("downloading, {0}%", args.ProgressPercentage * 95 / 100), args.ProgressPercentage * 95 / 100); }); wc.DownloadDataCompleted += (sender, args) => { UpdateStatus("download complete, running installer", 100); string appPath = Path.GetTempPath(); string dest = Path.Combine(appPath, "CNCMaps_update"); int suffixNr = 0; while (File.Exists(dest + (suffixNr > 0 ? suffixNr.ToString() : "") + ".exe")) { suffixNr++; } dest += (suffixNr > 0 ? suffixNr.ToString() : "") + ".exe"; File.WriteAllBytes(dest, args.Result); // invoke var psi = new ProcessStartInfo(dest); psi.Arguments = "/Q"; Process.Start(psi); Close(); }; // trigger it all wc.DownloadDataAsync(address); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.activity_main); //Reference swiperefresh layout, set color scheme classSwipeRefresh = FindViewById <SwipeRefreshLayout>(Resource.Id.swipeLayout); classSwipeRefresh.SetColorScheme(Android.Resource.Color.HoloBlueBright, Android.Resource.Color.HoloOrangeLight, Android.Resource.Color.HoloRedLight, Android.Resource.Color.HoloGreenLight); //Initilize UI Components myListView = FindViewById <ListView>(Resource.Id.myListView); editSearch = FindViewById <EditText>(Resource.Id.editSearch); headerAddressLine = FindViewById <TextView>(Resource.Id.headerAddressLine); headerCity = FindViewById <TextView>(Resource.Id.headerCity); headerState = FindViewById <TextView>(Resource.Id.headerState); headerZipCode = FindViewById <TextView>(Resource.Id.headerZipCode); //Adjust Search bar to be invisable and viewstates to gone editSearch.Alpha = 0; editSearch.Visibility = ViewStates.Gone; //Activate customer toolbar toolBar = FindViewById <Toolbar>(Resource.Id.toolbar); SetSupportActionBar(toolBar); SupportActionBar.Title = ""; //Download data from MYSQL Using PHP mProgressBar = FindViewById <ProgressBar>(Resource.Id.progressBar); mClient = new WebClient(); mUrl = new Uri("http://192.168.1.22:80/christmaslightsPHP/getAddresses.php"); mClient.DownloadDataAsync(mUrl); //Events myListView.ItemClick += MyListView_ItemClick; classSwipeRefresh.Refresh += ClassSwipeRefresh_Refresh; editSearch.TextChanged += EditSearch_TextChanged; headerAddressLine.Click += HeaderAddressLine_Click; headerCity.Click += HeaderCity_Click; headerState.Click += HeaderState_Click; headerZipCode.Click += HeaderZipCode_Click; mClient.DownloadDataCompleted += MClient_DownloadDataCompleted; }
private void buttonDownload_Click_1(object sender, EventArgs e) { try { labelPleaseWait.Text = Configuration.Settings.Language.General.PleaseWait; buttonOK.Enabled = false; buttonDownload.Enabled = false; Refresh(); Cursor = Cursors.WaitCursor; //TODO: Include d3dcompiler_43.dll in zip ? string url = "https://github.com/SubtitleEdit/support-files/blob/master/mpv/mpv-dll-" + IntPtr.Size * 8 + ".zip?raw=true"; var wc = new WebClient { Proxy = Utilities.GetProxy() }; wc.DownloadDataCompleted += wc_DownloadDataCompleted; wc.DownloadProgressChanged += (o, args) => { labelPleaseWait.Text = Configuration.Settings.Language.General.PleaseWait + " " + args.ProgressPercentage + "%"; }; wc.DownloadDataAsync(new Uri(url)); } catch (Exception exception) { labelPleaseWait.Text = string.Empty; buttonOK.Enabled = true; if (!Configuration.IsRunningOnLinux()) { buttonDownload.Enabled = true; } else { buttonDownload.Enabled = false; } Cursor = Cursors.Default; MessageBox.Show(exception.Message + Environment.NewLine + Environment.NewLine + exception.StackTrace); } }
public void StartDownload() { WC.DownloadDataCompleted += new DownloadDataCompletedEventHandler((sender, e) => { if (!e.Cancelled) { if (e.Error == null) { Form1.ExtFile.Add(Path.GetFileNameWithoutExtension(FileName), new MemoryStream(e.Result)); if (!form.LogForm.iscolse) { if (form.LogForm.InvokeRequired) { form.LogForm.BeginInvoke(new Action(delegate { form.LogForm.richTextBox1.AppendText(FileName + " 下載完成\r\n"); })); } else { form.LogForm.richTextBox1.AppendText(FileName + " 下載完成\r\n"); } } } } IsCancelled = e.Cancelled; if (!IsCancelled) { Error = (e.Error != null ? e.Error.Message : ""); } IsDone = true; WC.Dispose(); WC = null; }); WC.DownloadProgressChanged += new DownloadProgressChangedEventHandler((sender, e) => { KBytesReceived = (int)(e.BytesReceived / 1024); TotalKBytesToReceive = (int)(e.TotalBytesToReceive / 1024); }); WC.DownloadDataAsync(new Uri(URL)); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); RequestWindowFeature(WindowFeatures.NoTitle); //If the NavUpdate service somehow stayed running, kill it StopService(new Intent(this, typeof(NavUpdateService))); //JUST IN CASE // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); //Intialize web clients for downloading info from the server mClient = new WebClient(); mClient1 = new WebClient(); //Download lot list mClient.DownloadDataAsync(new Uri("http://jamesljenk.pythonanywhere.com/lots/")); mClient.DownloadDataCompleted += MClient_DownloadLotDataCompleted; //Load custom font tf = Typeface.CreateFromAsset(Assets, "transformersmovie.ttf"); //Change the main title text view font to custom font and make it bigger TextView mttv = FindViewById <TextView>(Resource.Id.MainTitleTextView); mttv.SetTypeface(tf, TypefaceStyle.Normal); mttv.SetTextSize(ComplexUnitType.Dip, 60); lotIndex = 0; //Change color of drop down menu lotChooser = FindViewById <Spinner>(Resource.Id.LotPickSpinner); lotChooser.SetBackgroundColor(Color.DarkGray); //Create event handler for menu item selection lotChooser.ItemSelected += new EventHandler <AdapterView.ItemSelectedEventArgs>(lotChooser_ItemSelected); //Assign method to run on button click parkButton = FindViewById <Button>(Resource.Id.ParkMeButton); parkButton.Click += StartNavigation; //Assign delegate method to run on button click ImageButton menubutton = FindViewById <ImageButton>(Resource.Id.MainMenuButton); menubutton.Click += delegate { StartActivity(typeof(MainMenuActivity)); }; }
private void buttonDownload_Click(object sender, EventArgs e) { try { labelPleaseWait.Text = LanguageSettings.Current.General.PleaseWait; buttonOK.Enabled = false; buttonDownload.Enabled = false; buttonDownloadAll.Enabled = false; comboBoxDictionaries.Enabled = false; Refresh(); Cursor = Cursors.WaitCursor; int index = comboBoxDictionaries.SelectedIndex; _downloadLink = _dictionaryDownloadLinks[index]; string url = _dictionaryDownloadLinks[index]; SelectedEnglishName = _englishNames[index]; var wc = new WebClient { Proxy = Utilities.GetProxy() }; wc.DownloadDataCompleted += wc_DownloadDataCompleted; wc.DownloadProgressChanged += (o, args) => { labelPleaseWait.Text = LanguageSettings.Current.General.PleaseWait + " " + args.ProgressPercentage + "%"; }; wc.DownloadDataAsync(new Uri(url)); } catch (Exception exception) { labelPleaseWait.Text = string.Empty; buttonOK.Enabled = true; buttonDownload.Enabled = true; buttonDownloadAll.Enabled = true; comboBoxDictionaries.Enabled = true; Cursor = Cursors.Default; MessageBox.Show(exception.Message + Environment.NewLine + Environment.NewLine + exception.StackTrace); } }
void downloadNextJob() { if (jobQueue.Count > 0) { DownloadJob job = jobQueue[jobQueue.Count - 1]; //if (downloadPhysics) filename = "RBRCIT\\physics\\" + c.physics + ".zip"; //else filename = "Cars\\" + c.folder + ".7z"; currentJob++; label1.Text = job.title + " (" + currentJob + " of " + totalJobs + " Files)"; label3.Text = job.URL.Replace("%20", " "); using (var client = new WebClient()) { client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged); client.DownloadDataCompleted += Client_DownloadDataCompleted; Uri u = new Uri(job.URL); client.DownloadDataAsync(u, client); } } else { Close(); } }
public void LoadImageDirectly(Uri uri) { var webClient = new WebClient(); MWCApp.LogDebug("Get speaker image directly, bypassing the ImageLoader which is taking too long"); webClient.DownloadDataCompleted += (sender, e) => { try { //var image = new global::Android.Graphics.Drawables.BitmapDrawable(bitmap); var byteArray = e.Result; MemoryStream ms = new MemoryStream(byteArray, 0, byteArray.Length); ms.Write(byteArray, 0, byteArray.Length); ms.Position = 0; var d = new global::Android.Graphics.Drawables.BitmapDrawable(ms); RunOnUiThread(() => { MWCApp.LogDebug("DETAILS speaker.ImageUrl"); imageview.SetImageDrawable(d); }); } catch (Exception ex) { MWCApp.LogDebug("Image error: " + ex); } }; webClient.DownloadDataAsync(uri); }
public static async Task ConcurrentOperations_Throw() { await LoopbackServer.CreateServerAsync((server, url) => { var wc = new WebClient(); Task ignored = wc.DownloadDataTaskAsync(url); // won't complete Assert.Throws<NotSupportedException>(() => { wc.DownloadData(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadDataAsync(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadDataTaskAsync(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadString(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadStringAsync(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadStringTaskAsync(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadFile(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadFileAsync(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadFileTaskAsync(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadData(url, new byte[42]); }); Assert.Throws<NotSupportedException>(() => { wc.UploadDataAsync(url, new byte[42]); }); Assert.Throws<NotSupportedException>(() => { wc.UploadDataTaskAsync(url, new byte[42]); }); Assert.Throws<NotSupportedException>(() => { wc.UploadString(url, "42"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadStringAsync(url, "42"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadStringTaskAsync(url, "42"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadFile(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadFileAsync(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadFileTaskAsync(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadValues(url, new NameValueCollection()); }); Assert.Throws<NotSupportedException>(() => { wc.UploadValuesAsync(url, new NameValueCollection()); }); Assert.Throws<NotSupportedException>(() => { wc.UploadValuesTaskAsync(url, new NameValueCollection()); }); return Task.CompletedTask; }); }
// it's actually impossible to really show this old-style in a Windows Store app // the non-async APIs just don't exist :-) public void DownloadHomepage() { var webClient = new WebClient(); // not in Windows Store APIs webClient.DownloadStringCompleted += (sender, e) => { if (e.Cancelled || e.Error != null) { // do something with error } string contents = e.Result; int length = contents.Length; Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ResultTextView.Text += "Downloaded the html and found out the length.\n\n"; }); webClient.DownloadDataCompleted += (sender1, e1) => { if (e1.Cancelled || e1.Error != null) { // do something with error } SaveBytesToFile(e1.Result, "team.jpg"); Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ResultTextView.Text += "Downloaded the image.\n"; var img = ApplicationData.Current.LocalFolder.GetFileAsync("team.jpg"); var i = new BitmapImage(new Uri(img.Path, UriKind.Absolute)); DownloadedImageView.Source = i; }); if (downloaded != null) downloaded(length); }; webClient.DownloadDataAsync(new Uri("http://xamarin.com/images/about/team.jpg")); }; webClient.DownloadStringAsync(new Uri("http://xamarin.com/")); }
protected void OnTestButtonClicked(object sender, EventArgs e) { testButton.State = Gtk.StateType.Insensitive; speedStatus.Text = "Testing... "; WebClient japan = new WebClient (); japan.Proxy = new WebProxy ("127.0.0.1:13370"); japan.DownloadDataAsync (new Uri ("http://ipv4.download.thinkbroadband.com:8080/5MB.zip")); Stopwatch tmr = new Stopwatch (); tmr.Start (); double jSpeed; japan.DownloadDataCompleted += delegate(object sdr, DownloadDataCompletedEventArgs E) { if (true) { speedStatus.Text = ""; jSpeed = (5000000 / 1024.0) / (tmr.ElapsedMilliseconds / 1000); GLib.Timeout.Add (200, updateStatus); theSpeed = jSpeed.ToString ().Substring (0, 6); theSpeed = "Result: " + Math.Round (jSpeed).ToString () + " KiB/s"; tmr.Reset (); tmr.Stop (); japan.CancelAsync (); japan.CancelAsync (); japan.CancelAsync (); testButton.Sensitive = true; } }; }
public static void DownloadData_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadData((string)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadData((Uri)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadDataAsync((Uri)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadDataAsync((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadDataTaskAsync((string)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadDataTaskAsync((Uri)null); }); }