public static async Task <byte[]> DownloadDbFile(string address)
        {
            var webClient = new System.Net.WebClient();
            var request   = await webClient.DownloadDataTaskAsync(address);

            return(request);
        }
        async Task ShareTapped()
        {
            //await Xamarin.Essentials.Share.RequestAsync(new Xamarin.Essentials.ShareTextRequest
            //{
            //    Uri = string.Format("https://music.163.com/song/media/outer/url?id={0}.mp3",NowSongInfo.id),
            //    Title = "共享歌曲"
            //});
            string downloadurl = string.Format("https://music.163.com/song/media/outer/url?id={0}.mp3", NowSongInfo.id);
            var    fn          = NowSongInfo.name + "." + musicInfo.data[0].encodeType;
            var    file        = System.IO.Path.Combine(Xamarin.Essentials.FileSystem.CacheDirectory, fn);

            using (await XF.Material.Forms.UI.Dialogs.MaterialDialog.Instance.LoadingDialogAsync(message: "生成音乐文件中......", new XF.Material.Forms.UI.Dialogs.Configurations.MaterialLoadingDialogConfiguration {
                TintColor = Color.FromHex("#94BBFF")
            }))
            {
                await Task.Run(async() =>
                {
                    System.Net.WebClient webClient = new System.Net.WebClient();
                    byte[] data = await webClient.DownloadDataTaskAsync(downloadurl);
                    System.IO.File.WriteAllBytes(file, data);
                    await Xamarin.Essentials.Share.RequestAsync(new Xamarin.Essentials.ShareFileRequest
                    {
                        Title = Title,
                        File  = new Xamarin.Essentials.ShareFile(file, "*/*")
                    });
                });
            };
        }
        public static async Task <BitmapImage> LoadWebPImageAsync(string url)
        {
            try
            {
                if (string.IsNullOrEmpty(url))
                {
                    return(null);
                }
                System.Net.WebClient wc = new System.Net.WebClient();
                wc.Headers.Add("Referer", "https://hitomi.la/");
                Byte[] MyData = await wc.DownloadDataTaskAsync(url);

                wc.Dispose();
                WebP         webP   = new WebP();
                Bitmap       bitmap = webP.Decode(MyData);
                MemoryStream ms     = new MemoryStream();
                bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                var bi = new BitmapImage();
                bi.BeginInit();
                bi.StreamSource = ms;
                bi.CacheOption  = BitmapCacheOption.OnLoad;
                bi.EndInit();
                return(bi);
            }
            catch
            {
                return(null);
            }
        }
        public async Task <IEnumerable <Account> > GetListOfAccountsAsync()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(_serviceURI))
                {
                    return(DummyAccounts()); // In case user hasn't set the uri, return instrctions in the list
                }
                System.Net.WebClient client = new System.Net.WebClient();
                var response = await client.DownloadDataTaskAsync(_serviceURI);

                if (response != null)
                {
                    var content = Encoding.UTF8.GetString(response, 0, response.Length);
                    var Items   = JsonConvert.DeserializeObject <List <Account> >(content, _settings);
                    return(Items);
                }
            }
            catch (Exception ex)
            {
                _loggingService?.Error(ex);
                throw ex;
            }
            return(new List <Account>());
        }
Exemple #5
0
 public static Task <byte[]> DownloadDataTaskAsync(string url)
 {
     using (var client = new System.Net.WebClient())
     {
         return(client.DownloadDataTaskAsync(url));
     }
 }
        public async Task <ServiceResult <byte[]> > GetByteArray(string url)
        {
            var serviceResult = new ServiceResult <byte[]>();

            byte[] byteArray;
            using (var webClient = new System.Net.WebClient())
            {
                try
                {
                    byteArray = await webClient.DownloadDataTaskAsync(url);
                }
                catch (Exception ex)
                {
                    serviceResult.Success           = false;
                    serviceResult.Error.Code        = ErrorStatusCode.BudRequest;
                    serviceResult.Error.Description = ex.Message;
                    return(serviceResult);
                }
            }

            if (byteArray.Length == 0)
            {
                serviceResult.Success           = false;
                serviceResult.Error.Code        = ErrorStatusCode.BudRequest;
                serviceResult.Error.Description = "byteArray is null.";
                return(serviceResult);
            }

            serviceResult.Success = true;
            serviceResult.Result  = byteArray;

            return(serviceResult);
        }
Exemple #7
0
        private static async Task <byte[]> DownloadKoobooZip(System.Net.DownloadProgressChangedEventHandler downloadProgressChanged)
        {
            string serverUrl = AppSettings.ConvertApiUrl + "/_api/upgrade/DownloadUpgradePackage";
            var    client    = new System.Net.WebClient();

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

            Uri uri   = new Uri(serverUrl);
            var bytes = await client.DownloadDataTaskAsync(uri);

            if (client.ResponseHeaders.AllKeys.Contains("filehash"))
            {
                var hash = client.ResponseHeaders["filehash"];
                if (hash != null)
                {
                    Guid hashguid = default(Guid);

                    if (Guid.TryParse(hash, out hashguid))
                    {
                        var newhash = Lib.Security.Hash.ComputeGuid(bytes);
                        if (hashguid == newhash)
                        {
                            return(bytes);
                        }
                    }
                }
            }
            return(null);
        }
Exemple #8
0
        public async Task <ImageEntry> DownloadCoverArt(string url, IProgress <int> progress = null)
        {
            var doc = webClient.Load(url).DocumentNode;

            var container = doc.SelectSingleNodeById("main");

            var src = container
                      ?.SelectSingleNode(".//img")
                      .GetAttributeValue("src", null);

            if (src == null)
            {
                throw new ScraperException($"Could not find cover art in page: {url}");
            }

            var baseUrl  = new Uri(url);
            var imageUrl = new Uri(baseUrl, src);

            using var client = new System.Net.WebClient();

            if (progress != null)
            {
                client.DownloadProgressChanged += (_, args) => { progress.Report(args.ProgressPercentage); };
            }

            var data = await client.DownloadDataTaskAsync(imageUrl);

            return(new ImageEntry
            {
                Data = data,
                Url = imageUrl
            });
        }
Exemple #9
0
        private static async Task <byte[]> DownloadKoobooZip(string url)
        {
            var client = new System.Net.WebClient();

            Uri uri   = new Uri(url);
            var bytes = await client.DownloadDataTaskAsync(uri);

            if (client.ResponseHeaders.AllKeys.Contains("filehash"))
            {
                var hash = client.ResponseHeaders["filehash"];
                if (hash != null)
                {
                    Guid hashguid = default(Guid);

                    if (Guid.TryParse(hash, out hashguid))
                    {
                        var newhash = Lib.Security.Hash.ComputeGuid(bytes);
                        if (hashguid == newhash)
                        {
                            return(bytes);
                        }
                    }
                }
            }
            return(bytes);
        }
Exemple #10
0
        public async Task <Stream> GetStreamFromUrl(string url)
        {
            byte[] imageData = null;

            using (var wc = new System.Net.WebClient())
                return(new MemoryStream(await wc.DownloadDataTaskAsync(url)));
        }
 public byte[] DownloadFileContent(string fileUrl)
 {
     byte[] contentArray = null;
     using (var wc = new System.Net.WebClient()) {
         contentArray = wc.DownloadDataTaskAsync(new Uri(fileUrl)).Result;
     }
     return(contentArray);
 }
Exemple #12
0
        public async Task <ActionResult> GetXml()
        {
            System.Net.WebClient wc = new System.Net.WebClient();

            var data = await wc.DownloadDataTaskAsync(new Uri("http://localhost:24762/PackageAPI/GetHealthAssessment?id=12&xpath=/data/Life"));

            return(File(data, "text/xml"));
        }
Exemple #13
0
        private static async Task DownloadMonacoAsync()
        {
            var currentMonacoVersion = Data.AppSettings.MonacoVersion ?? "";
            var fileBakName          = MonacoZipPath + ".bak";

            if (currentMonacoVersion != _monacoVersion || !_zipExist)
            {
                try
                {
                    _isLoadding = true;
                    var client = new System.Net.WebClient();
                    var uri    = new Uri($"https://cdn.jsdelivr.net/gh/kooboo/monaco@master/vs{_monacoVersion}.zip");
                    var bytes  = await client.DownloadDataTaskAsync(uri);

                    if (bytes != null && bytes.Length > 0)
                    {
                        if (File.Exists(MonacoZipPath))
                        {
                            VirtualResources.Setup(s => s.UnloadZip(MonacoZipPath));
                            if (File.Exists(fileBakName))
                            {
                                File.Delete(fileBakName);
                            }
                            File.Move(MonacoZipPath, fileBakName);
                        }

                        File.WriteAllBytes(MonacoZipPath, bytes);

                        VirtualResources.Setup(s => s.LoadZip(
                                                   MonacoZipPath,
                                                   AppSettings.RootPath,
                                                   new Lib.VirtualFile.Zip.ZipOption
                        {
                            Cache = true
                        }));
                        _zipExist = true;
                    }

                    AppSettings.SetConfigValue("MonacoVersion", _monacoVersion);
                    if (File.Exists(fileBakName))
                    {
                        File.Delete(fileBakName);
                    }
                    _isLoadding = false;
                }
                catch (Exception e)
                {
                    _isLoadding = false;
                    if (File.Exists(fileBakName))
                    {
                        File.Move(fileBakName, MonacoZipPath);
                    }
                    AppSettings.SetConfigValue("MonacoVersion", currentMonacoVersion);
                    _zipExist = File.Exists(MonacoZipPath);
                    throw e;
                }
            }
        }
Exemple #14
0
 public async Task <Stream> GetStream(Uri url)
 {
     byte[] data = null;
     using (var wc = new System.Net.WebClient())
     {
         data = await wc.DownloadDataTaskAsync(url);
     }
     return((new MemoryStream(data)) as Stream);
 }
Exemple #15
0
        public async Task <IActionResult> GetBuyOrders()
        {
            using (var client = new System.Net.WebClient())
            {
                var databuy = await client.DownloadDataTaskAsync(new Uri("https://c-cex.com/t/api_pub.html?a=getorderbook&market=btc-usd&type=buy&depth=100"));

                return(Ok(System.Text.Encoding.ASCII.GetString(databuy)));
            }
        }
Exemple #16
0
        public static async Task <bool> GetUpdate()
        {
            TaskCompletionSource <bool> r = new TaskCompletionSource <bool>();
            string currentVersion         = VersionTracking.CurrentVersion;
            string result = CloudMusic.ApiHelper.HttpClient.HttpGet(url);

            if (!result.Equals("err"))
            {
                GitHubReleasesModel releasesModel = JsonConvert.DeserializeObject <GitHubReleasesModel>(result);
                string lastReleasesVersion        = releasesModel.tag_name;
                string IgnoreVersion = Preferences.Get("IgnoreVersion", "");
                if (lastReleasesVersion.Equals(IgnoreVersion))
                {
                    r.SetResult(false);
                    return(await r.Task);
                }
                string downloadurl = releasesModel.assets[0].browser_download_url;
                size = releasesModel.assets[0].size;
                bool hasupdate = ContainsVersion(currentVersion, lastReleasesVersion);
                if (hasupdate && Device.RuntimePlatform.Equals(Device.Android))
                {
                    Device.BeginInvokeOnMainThread(async() =>
                    {
                        try
                        {
                            string content = string.Format("{0}\r\n\r\n大小({1}MB)", releasesModel.body, ((double)size / 1024 / 1024).ToString("f2"));
                            if (await App.Current.MainPage.DisplayAlert("发现新版本" + lastReleasesVersion, content, "更新", "忽略此版本"))
                            {
                                DependencyService.Get <IToast>().ShortAlert("更新已在后台下载,请稍后");
                                System.Net.WebClient webClient     = new System.Net.WebClient();
                                webClient.DownloadProgressChanged += WebClient_DownloadProgressChanged;
                                webClient.DownloadDataCompleted   += WebClient_DownloadDataCompleted;
                                byte[] data     = await webClient.DownloadDataTaskAsync(downloadurl);
                                string fileName = releasesModel.assets[0].name;
                                DependencyService.Get <IFileOpener>().OpenFile(data, fileName);
                            }
                            else
                            {
                                Preferences.Set("IgnoreVersion", lastReleasesVersion);
                            }
                        }
                        catch (Exception ex)
                        {
                            DependencyService.Get <IToast>().ShortAlert("更新下载失败:" + ex.Message);
                            DependencyService.Get <INotification>().NotificationCancel(1);
                        }
                    });
                }
                else
                {
                    r.SetResult(false);
                    return(await r.Task);
                }
            }
            r.SetResult(true);
            return(await r.Task);
        }
        public async Task <MemoryStream> GetContent(string url)
        {
            var client = new System.Net.WebClient();

            byte[] data = await client.DownloadDataTaskAsync(url);

            MemoryStream content = new MemoryStream(data);

            return(content);
        }
Exemple #18
0
        private static async Task DownloadMonacoAsync()
        {
            var dir                  = Path.Combine(Data.AppSettings.RootPath, "_Admin/Scripts/lib/");
            var extractDir           = Path.Combine(dir, "vs");
            var fileName             = dir + $"vs{_monacoVersion}.zip";
            var currentMonacoVersion = Data.AppSettings.MonacoVersion ?? "";

            if (currentMonacoVersion != _monacoVersion)
            {
                try
                {
                    _isLoadding = true;
                    var client = new System.Net.WebClient();
                    var uri    = new Uri($"https://cdn.jsdelivr.net/gh/kooboo/monaco@master/vs{_monacoVersion}.zip");
                    var bytes  = await client.DownloadDataTaskAsync(uri);

                    if (bytes != null)
                    {
                        if (Directory.Exists(extractDir))
                        {
                            Directory.Delete(extractDir, true);
                        }
                        IOHelper.EnsureFileDirectoryExists(dir);
                        if (bytes.Length > 0)
                        {
                            File.WriteAllBytes(fileName, bytes);
                        }
                    }

                    ZipFile.ExtractToDirectory(fileName, dir);
                    if (File.Exists(fileName))
                    {
                        File.Delete(fileName);
                    }
                    Data.AppSettings.SetConfigValue("MonacoVersion", _monacoVersion);
                    _isLoadding = false;
                }
                catch (Exception e)
                {
                    _isLoadding = false;
                    if (Directory.Exists(extractDir))
                    {
                        Directory.Delete(extractDir, true);
                    }
                    if (File.Exists(fileName))
                    {
                        File.Delete(fileName);
                    }
                    Data.AppSettings.SetConfigValue("MonacoVersion", currentMonacoVersion);
                    throw e;
                }
            }
        }
        private async Task <ImageSource> ImageSourceDownloadAsyn(string url)
        {
            byte[]      vs;
            ImageSource imageSource;
            var         client = new System.Net.WebClient();

            vs = await client.DownloadDataTaskAsync(new Uri(url));

            imageSource = ImageSource.FromStream(() => new MemoryStream(vs));

            return(imageSource);
        }
Exemple #20
0
        async Task <IActionResult> DownloadFileAsync(string fileName)
        {
            using (var net = new System.Net.WebClient())
            {
                byte[] data = await net.DownloadDataTaskAsync(fileName);

                return(new FileContentResult(data, "application/pdf")
                {
                    FileDownloadName = "file_name_here.pdf"
                });
            }
        }
        public static async Task <byte[]> LoadUrlImageAsync(string url)
        {
            if (string.IsNullOrEmpty(url))
            {
                return(null);
            }
            System.Net.WebClient wc = new System.Net.WebClient();
            wc.Headers.Add("Referer", "https://" + new Uri(url).Host);
            Byte[] Data = await wc.DownloadDataTaskAsync(url);

            wc.Dispose();
            return(Data);
        }
Exemple #22
0
        public async Task <string> NavigationControl()
        {
            string result = string.Empty;

            byte[] bytes;
            System.Net.WebClient mClient = new System.Net.WebClient();
            string urlRef = "navigationControl.php" + "?" + "id=" + mPositionID.ToString();
            Uri    url    = new Uri(ConfigManager.WebService + "/" + urlRef);

            bytes = await mClient.DownloadDataTaskAsync(url);

            result = System.Text.Encoding.UTF8.GetString(bytes);
            return(result);
        }
Exemple #23
0
 private async Task <byte[]> GetImageData(string url)
 {
     byte[] image_data = null;
     try
     {
         Uri image_url = new Uri(url);
         var webClient = new System.Net.WebClient();
         image_data = await webClient.DownloadDataTaskAsync(image_url);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
     return(image_data);
 }
Exemple #24
0
        /// <summary>
        /// ダウンロードプレビュー用
        /// ImageMagicを使ってサムネイルサイズに加工してから取得する
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        public async Task <ImageSource> DownLoadPreview(string uri)
        {
            try
            {
                using var client = new System.Net.WebClient();
                var bytes = await client.DownloadDataTaskAsync(new Uri(uri));

                var image = await ImageSourceHelper.LoadThumbnailFromByteAsync(bytes, 128, 128);

                return(image);
            }
            catch
            {
                return(ThumbnailService.NoneImageSource);
            }
        }
        public static async Task <ImageSource> GetImageSourceFromUrlAsync(string url)
        {
            byte[]       imageData = null;
            MemoryStream ms        = null;

            try
            {
                using (var wc = new System.Net.WebClient())
                {
                    imageData = await wc.DownloadDataTaskAsync(url);
                }
                ms = new MemoryStream(imageData);
            }
            catch { }

            return(ImageSource.FromStream(() => ms));
        }
        public static async Task <string> DownloadImageFromUrlSaveLocal(string ImageUrl)
        {
            using (var webClient = new System.Net.WebClient())
            {
                var    filename  = ImageUrl.Split('/').Last();
                var    extension = Path.GetExtension(filename);
                var    fileName  = filename.Split('.').First();
                byte[] imageBytes;
                var    filePath  = Path.Combine(LocalAttachmentFolder, $"{fileName}.{extension}");
                var    fileCount = Directory.GetFiles(LocalAttachmentFolder).Count();
                filePath   = Path.Combine(LocalAttachmentFolder, $"{fileName}_{fileCount}.{extension}");
                imageBytes = await webClient.DownloadDataTaskAsync(new Uri(ImageUrl));

                File.WriteAllBytes(filePath, imageBytes);
                return(filePath);
            }
        }
        private async void Download(string uri, string dest, Action <int> onChange, Action onDone)
        {
            if (webClient.IsBusy)
            {
                return;
            }

            webClient.DownloadProgressChanged += (s, e) => onChange?.Invoke(e.ProgressPercentage);

            var data = await webClient.DownloadDataTaskAsync(new Uri(uri));

            using (var stream = new FileStream(dest, FileMode.OpenOrCreate))
            {
                await stream.WriteAsync(data, 0, data.Length);
            }

            onDone?.Invoke();
            GC.Collect();
        }
        public async void Downlaod_mp3_Url(string url, string audioFileName, Xamarin.Forms.ActivityIndicator LoadingDownloadProgress, Xamarin.Forms.Label DownloadingLabel)
        {
            _audioFileName = audioFileName;
            LoadingDownloadProgress.IsRunning = true;
            DownloadingLabel.IsVisible        = true;
            //	Android.Widget.Toast.MakeText(Android.App.Application.Context, _audioFileName + " Downloading..", Android.Widget.ToastLength.Long).Show();
            var webClient = new System.Net.WebClient();

            //var url = new Uri("http://www.maninblack.org/demos/SitDownShutUp.mp3");
            //  string local = "/sdcard/Download/abc.mp3";
            byte[] bytes = null;

            webClient.DownloadProgressChanged += WebClient_DownloadProgressChanged;

            try
            {
                bytes = await webClient.DownloadDataTaskAsync(url);
            }
            catch (System.Threading.Tasks.TaskCanceledException)
            {
                //  Android.Widget.Toast.MakeText(Android.App.Application.Context, "Task Canceled!", Android.Widget.ToastLength.Long).Show();
                return;
            }
            catch (Exception a)
            {
                //Android.Widget.Toast.MakeText(Android.App.Application.Context,a.InnerException.Message, Android.Widget.ToastLength.Long);
                Download_Completed = false;
                return;
            }

            Java.IO.File documentsPath = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads), "");
            string       localFilename = documentsPath + "/" + audioFileName;

            //Save the Mp3 using writeAsync

            System.IO.FileStream fs = new System.IO.FileStream(localFilename, System.IO.FileMode.OpenOrCreate);
            await fs.WriteAsync(bytes, 0, bytes.Length);

            fs.Close();
            LoadingDownloadProgress.IsRunning = false;
            DownloadingLabel.IsVisible        = false;
            Download_Completed = false;
        }
        public static async Task <byte[]> LoadUrlWebPImageAsync(string url)
        {
            if (string.IsNullOrEmpty(url))
            {
                return(null);
            }
            System.Net.WebClient wc = new System.Net.WebClient();
            wc.Headers.Add("Referer", "https://" + new Uri(url).Host);
            Byte[] MyData = await wc.DownloadDataTaskAsync(url);

            wc.Dispose();
            WebP         webP   = new WebP();
            Bitmap       bitmap = webP.Decode(MyData);
            MemoryStream ms     = new MemoryStream();

            bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            byte[] data = ms.ToArray();
            ms.Dispose();
            return(data);
        }
Exemple #30
0
        private void tbbRefresh_Click(object sender, EventArgs e)
        {
            this.Entries.Clear();
            fpnlContainer.Controls.Clear();
            _index = 1;

            try
            {
                if (wc == null)
                {
                    wc                        = new System.Net.WebClient();
                    wc.CachePolicy            = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
                    wc.DownloadDataCompleted += Wc_DownloadDataCompleted;
                }

                wc.DownloadDataTaskAsync(new Uri($"{_urlGallery}index-v10.xml"));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }