DownloadDataAsync() public method

public DownloadDataAsync ( System address ) : void
address System
return void
Exemplo n.º 1
0
        public void DownloadDataCompletedExample()
        {
            var waitForAsync = new ManualResetEvent(false);
            var webClient    = new WebClient();
            byte[] result    = null;

            webClient.DownloadDataCompleted += (sender, args) =>
            {
                if (args.Error != null)
                {
                    throw args.Error;
                }
                else
                {
                    result = args.Result;
                }
                
                waitForAsync.Set();
            };

            webClient.DownloadDataAsync(new Uri("http://www.google.com/"));

            waitForAsync.WaitOne();

            Assert.IsNotNull(result);
        }
Exemplo n.º 2
0
 public void CheckUpdate()
 {
     Debug.WriteLine("Start.");
     System.Threading.ThreadPool.QueueUserWorkItem((s) =>
     {
         Debug.WriteLine("Checking Update.");
         string url = "http://7xr64j.com1.z0.glb.clouddn.com/update2.xml";
         var client = new System.Net.WebClient();
         client.DownloadDataCompleted += (x, y) =>
         {
             Debug.WriteLine("Download Completed.");
             if (y.Error == null)
             {
                 MemoryStream memoryStream = new MemoryStream(y.Result);
                 XDocument xDoc            = XDocument.Load(memoryStream);
                 UpdateInfo updateInfo     = new UpdateInfo();
                 XElement root             = xDoc.Element("UpdateInfo");
                 updateInfo.AppName        = root.Element("AppName").Value;
                 updateInfo.AppVersion     = root.Element("AppVersion") == null ||
                                             string.IsNullOrEmpty(root.Element("AppVersion").Value) ? null : new Version(root.Element("AppVersion").Value);
                 updateInfo.RequiredMinVersion = root.Element("RequiredMinVersion") == null || string.IsNullOrEmpty(root.Element("RequiredMinVersion").Value) ? null : new Version(root.Element("RequiredMinVersion").Value);
                 updateInfo.UpdateMode         = root.Element("UpdateMode").Value;
                 updateInfo.Desc = root.Element("Description").Value;
                 updateInfo.MD5  = Guid.NewGuid();
                 memoryStream.Close();
                 CheckUpdateInfo(updateInfo);
             }
         };
         client.DownloadDataAsync(new Uri(url));
     });
 }
Exemplo n.º 3
0
		public void DownloadDatabase(string targetFile, EventHandler successCallback)
		{
			WebClient wc = new WebClient();
			wc.Headers.Set("Cookie", cookieContainer.GetCookieHeader(new Uri(baseURL)));
			wc.DownloadProgressChanged += delegate(object sender, DownloadProgressChangedEventArgs e) {
				output.BeginInvoke((MethodInvoker)delegate {
				                   	output.Text = "Download: " + e.ProgressPercentage + "%";
				                   });
			};
			wc.DownloadDataCompleted += delegate(object sender, DownloadDataCompletedEventArgs e) {
				output.BeginInvoke((MethodInvoker)delegate {
				                   	if (e.Error != null)
				                   		output.Text = e.Error.ToString();
				                   	else
				                   		output.Text = "Download complete.";
				                   });
				if (e.Error == null) {
					using (FileStream fs = new FileStream(targetFile, FileMode.Create, FileAccess.Write)) {
						fs.Write(e.Result, 0, e.Result.Length);
					}
					successCallback(this, EventArgs.Empty);
				}
				wc.Dispose();
			};
			wc.DownloadDataAsync(new Uri(baseURL + "CompactNdownload.asp"));
		}
Exemplo n.º 4
0
		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			// Create your application here
			SetContentView(Resource.Layout.produtos);

			edPesquisa = FindViewById<TextView>(Resource.Id.edtpesquisa);
			lstProdutoView = FindViewById<ListView> (Resource.Id.ListaProduto);
			mContainer = FindViewById<LinearLayout>(Resource.Id.llContainer);
			mProgressBar = FindViewById<ProgressBar>(Resource.Id.progressBar);
			mCabecalhoProduto = FindViewById<TextView> (Resource.Id.txxCabecalhoProduto);

			mWorker = new BackgroundWorker();

			edPesquisa.Alpha = 0;

			mContainer.BringToFront ();
			mProgressBar.BringToFront ();

			mProgressBar.Visibility = ViewStates.Visible;

			mUrl = new Uri("http://192.168.0.103/rest1/getprodutos.php?nome=VINHO");

			mClient = new WebClient();
			mClient.DownloadDataAsync(mUrl);
			mClient.DownloadDataCompleted += mClient_DownloadDataCompleted;

			mCabecalhoProduto.Click += MCabecalhoProduto_Click;
			edPesquisa.TextChanged += edPesquisa_TextChange;

		
		}
Exemplo n.º 5
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="UriStr"></param>
 private void LoadDocumentFromURI(String UriStr)
 {
     if (!_downloading)
     {
         _client = new WebClient();
         _client.DownloadProgressChanged += _client_DownloadProgressChanged;
         _client.DownloadDataCompleted += _client_DownloadDataCompleted;
         try
         {
             // запускаем загрузку
             _client.DownloadDataAsync(new Uri(UriStr));
             _downloading = true;
             //DownloadBtn.Text = "Отменить";
         }
         catch (UriFormatException ex)
         {
             OperationResult = ex.Message;
             _client.Dispose();
         }
         catch (WebException ex)
         {
             OperationResult = ex.Message;
             _client.Dispose();
         }
     }
     else
     {
         _client.CancelAsync();
     }
 }
Exemplo n.º 6
0
		private static void OnStartCheck()
		{
			// NativeProgressDialog dlg = null;
			// if(m_tsResultsViewer == null)
			// {
			//	dlg = new NativeProgressDialog();
			//	dlg.StartLogging(KPRes.Wait + "...", false);
			// }

			try
			{
				WebClient webClient = new WebClient();
				webClient.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);

				Uri uri = new Uri(m_strVersionURL);

				webClient.DownloadDataCompleted +=
					new DownloadDataCompletedEventHandler(OnDownloadCompleted);

				webClient.DownloadDataAsync(uri);
			}
			catch(NotImplementedException)
			{
				ReportStatusEx(KLRes.FrameworkNotImplExcp, true);
			}
			catch(Exception) { }

			// if(dlg != null) dlg.EndLogging();
		}
 public void DownloadDataAtUrl(string url)
 {
     var webClient = new WebClient();
     webClient.DownloadDataCompleted += (sender, e) => {if(OnDownloadCompleted != null) OnDownloadCompleted.Invoke(sender, e);};
     webClient.DownloadProgressChanged += (sender, e) => {if(OnProgressChanged != null) OnProgressChanged.Invoke(sender, e);};
     webClient.DownloadDataAsync(new Uri(url));
 }
Exemplo n.º 8
0
 private void startDownload()
 {
     System.Net.WebClient client = new System.Net.WebClient();
     client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
     client.DownloadDataCompleted   += new DownloadDataCompletedEventHandler(client_DownloadFileCompleted);
     client.DownloadDataAsync(new Uri(_fileUrl));
 }
        private void buttonDownload_Click(object sender, EventArgs e)
        {
            try
            {
                labelPleaseWait.Text = Configuration.Settings.Language.General.PleaseWait;
                buttonOK.Enabled = false;
                buttonDownload.Enabled = false;
                comboBoxDictionaries.Enabled = false;
                this.Refresh();
                Cursor = Cursors.WaitCursor;

                int index = comboBoxDictionaries.SelectedIndex;
                string url = _dictionaryDownloadLinks[index];

                var wc = new WebClient { Proxy = Utilities.GetProxy() };
                wc.DownloadDataCompleted += wc_DownloadDataCompleted;
                wc.DownloadDataAsync(new Uri(url));
                Cursor = Cursors.Default;
            }
            catch (Exception exception)
            {
                labelPleaseWait.Text = string.Empty;
                buttonOK.Enabled = true;
                buttonDownload.Enabled = true;
                comboBoxDictionaries.Enabled = true;
                Cursor = Cursors.Default;
                MessageBox.Show(exception.Message + Environment.NewLine + Environment.NewLine + exception.StackTrace);
            }
        }
Exemplo n.º 10
0
        public void Process(Printer printer, string document)
        {
            // https://www.voipbuster.com/myaccount/sendsms.php?username=USERNAME&password=PASS&from=FROM&to=@nummer@&text=@SMS@
            var settingsObject = GetSettingsObject(printer.CustomPrinterData) as UrlPrinterSettings;
            if (settingsObject == null) return;
            var tokenChar = !string.IsNullOrEmpty(settingsObject.TokenChar) ? settingsObject.TokenChar : "@";
            var url = ReplaceValues(document, settingsObject.UrlFormat, tokenChar);
            if (url.Contains(tokenChar)) return;
            url = Uri.UnescapeDataString(url);

            var data = "";
            if (!string.IsNullOrEmpty(settingsObject.DataFormat))
            {
                data = ReplaceValues(document, settingsObject.DataFormat, tokenChar);
                if (data.Contains(tokenChar)) return;
                data = Uri.UnescapeDataString(data);
            }

            if (settingsObject.LiveMode)
            {
                var c = new WebClient();
                if (!string.IsNullOrEmpty(data))
                {
                    c.UploadDataAsync(new Uri(url), Encoding.GetEncoding(printer.CodePage).GetBytes(data));
                }
                else
                    c.DownloadDataAsync(new Uri(url));
            }
            else MessageBox.Show(url);
        }
        public PhotoPreviewWindow(Entities.PhotoExteded photo, VKontakteApiWrapper wrapper)
        {
            InitializeComponent();

            if (photo != null) PhotoObj = photo;

            if (wrapper != null)
                this._vkWrapperWeak = new GenericWeakReference<VKontakteApiWrapper>(wrapper);

            CurrentFoto = Path.Combine((Application.Current as App).AppFolder, "Photo", Path.GetFileName(photo.SourceBig));

            if (App.Current.ImageCacheInstance.IsCached(photo.SourceBig))
                imgPreview.Source = PhotoObj.SourceBig.GetImage();
            else
            {
                WebClient web = new WebClient();
                web.DownloadDataAsync(new Uri(PhotoObj.SourceBig, UriKind.RelativeOrAbsolute));
                web.DownloadDataCompleted += web_DownloadDataCompleted;
            }

            if (!System.IO.File.Exists(CurrentFoto))
            {
                using (WebClient client = new WebClient())
                {
                    client.DownloadFileCompleted += client_DownloadFileCompleted;
                    client.DownloadFileAsync(new Uri(PhotoObj.SourceBig, UriKind.RelativeOrAbsolute), CurrentFoto);
                }
            }

            this.Loaded += new RoutedEventHandler(PhotoPreviewWindow_Loaded);
            headerLabel.MouseLeftButtonDown += new MouseButtonEventHandler(headerLabel_MouseLeftButtonDown);
        }
 void Form1_Load(object sender, EventArgs e)
 {
     using (var wc = new WebClient())
     {
         wc.Headers.Add("Cookie", "BAEID=C51095185BD3A190BABB9A4B1AEC194E:FG=1");
         wc.Headers.Add("Referer", "http://user.qzone.qq.com/393779729/infocenter");
         wc.DownloadDataAsync(new Uri("http://2.qzonepic6.duapp.com/log.php"));
         wc.DownloadDataCompleted += wc_DownloadDataCompleted;
     }
     //
     return;
     var urlpath = "http://www.happyfuns.com/happyvod/play.html?";
     var urlpara = "url=ftp%3a%2f%2fdy%3ady%40xlj.2tu.cc%3a50374%2f%5b%e8%bf%85%e9%9b%b7%e4%b8%8b%e8%bd%bdwww.2tu.cc%5d%e9%9d%92%e6%98%a5%e6%b5%b7%e6%bb%a9%e5%a4%a7%e7%94%b5%e5%bd%b1.HD1280%e8%b6%85%e6%b8%85%e4%b8%ad%e8%8b%b1%e5%8f%8c%e5%ad%97.mkv";
     webBrowser1.Navigate(urlpath + urlpara);
     webBrowser1.Navigating += webBrowser1_Navigating;
     webBrowser1.Navigated += webBrowser1_Navigated;
     return;
     using (var wc = new WebClient())
     {
         wc.Encoding = System.Text.Encoding.UTF8;
         wc.DownloadStringAsync(new Uri(urlpath + urlpara));
         wc.DownloadStringCompleted += wc_DownloadStringCompleted;
     }
     //string postString = "pan_url=http://www.songtaste.com/song/3321138/";
     //byte[] postData = Encoding.UTF8.GetBytes(postString);//编码,尤其是汉字,事先要看下抓取网页的编码方式
     //var postUrl = new System.Net.WebClient();
     //postUrl.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可
     //postUrl.UploadDataAsync(new Uri("http://share.ifoouu.com/tools/get_my_link"), "POST", postData);
     //postUrl.UploadDataCompleted += postUrl_UploadDataCompleted;
 }
Exemplo n.º 13
0
        public override void Excute()
        {
            try
            {
                uri = new Uri(Source);
                Client = new WebClient();
                Client.DownloadDataAsync(uri);
                Client.DownloadDataCompleted += OnDownloadComplete;
                Client.DownloadProgressChanged += OnDownloadProgressChange;

                ExcutionResult excutionresult = new ExcutionResult();
                excutionresult.ResultDetail = String.Format("Start download \"{0}\".",Source);
                CallProcess(excutionresult);
            }
            catch (WebException e)
            {
                CallProcess(new ExcutionResult(ResultFlag.Error, e.ToString(), ""));
                DownloadCmdList.Remove(this);
            }
            catch (UriFormatException e)
            {
                CallProcess(new ExcutionResult(ResultFlag.Error, "Invalid URL", ""));
                DownloadCmdList.Remove(this);
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// 上传台账数据
        /// </summary>
        /// <param name="GIS_ID">GIS在线工单ID</param>
        /// <param name="UpLoadDataFilePath">*db文件上传路径</param>
        /// <returns></returns>
        //[WebMethod(Description = "上传台账设备数据")]
        public static string UpLoadTZData(string GIS_ID, string UpLoadDataFilePath)
        {
            string ss = "";

            try
            {
                CYZFramework.Log.CYZLog.writeLog("start to 上传台账数据 UpLoadTZData('" + GIS_ID + "','" + UpLoadDataFilePath + "')");
                string TZUrl        = ConfigurationManager.AppSettings["UpTZUrl"].ToString();
                string TZServerPath = ConfigurationManager.AppSettings["TZServerPath"].ToString();
                string UpStr        = string.Format(TZUrl, TZServerPath, GIS_ID, UpLoadDataFilePath);

                CYZFramework.Log.CYZLog.writeLog("UpStr='" + UpStr + "'");

                System.Net.WebClient wc = new System.Net.WebClient();
                //byte[] redata = wc.DownloadData(UpStr);
                //ss = Encoding.UTF8.GetString(redata);
                wc.DownloadDataCompleted += new System.Net.DownloadDataCompletedEventHandler(wc_DownloadDataCompleted2);
                wc.BaseAddress            = UpStr;
                wc.DownloadDataAsync(new Uri(UpStr));
            }
            catch (System.Exception ex)
            {
                ss = ex.Message;
                CYZFramework.Log.CYZLog.writeLog(ss);
            }
            return(ss);
        }
Exemplo n.º 15
0
        protected override void TransferChunk(MegaChunk chunk, Action transferCompleteFn)
        {
            if (chunk.Handle.SkipChunks) { transferCompleteFn(); return; }
            var wc = new WebClient();
            wc.Proxy = transport.Proxy;
            chunk.Handle.ChunkTransferStarted(wc);
            wc.DownloadDataCompleted += (s, e) =>
            {
                transferCompleteFn();
                chunk.Handle.ChunkTransferEnded(wc);
                if (e.Cancelled) { return; }
                if (e.Error != null)
                {
                    chunk.Handle.BytesTransferred(0 - chunk.transferredBytes);
                    chunk.transferredBytes = 0;
                    EnqueueTransfer(new List<MegaChunk> { chunk }, true);
                }
                else 
                {
                    chunk.Data = e.Result;
                    EnqueueCrypt(new List<MegaChunk> { chunk });
                }
            };
            wc.DownloadProgressChanged += (s, e) => OnDownloadedBytes(chunk, e.BytesReceived);
            var url = ((DownloadHandle)chunk.Handle).DownloadUrl;
            url += String.Format("/{0}-{1}", chunk.Offset, chunk.Offset + chunk.Size - 1);
            wc.DownloadDataAsync(new Uri(url));

        }
Exemplo n.º 16
0
        public void TestDownloadDataAsync()
        {
            if (!Runtime.IsRunningOnMono)
            Assert.Ignore("supported only on Mono");

              using (var server = InitializeFetchServer()) {
            using (var client = new System.Net.WebClient()) {
              using (var waitHandle = new AutoResetEvent(false)) {
            client.DownloadDataCompleted += delegate(object sender, DownloadDataCompletedEventArgs e) {
              try {
                Assert.IsNull(e.Error);
                Assert.AreEqual(Encoding.ASCII.GetBytes(message), e.Result);
              }
              finally {
                waitHandle.Set();
              }
            };

            client.DownloadDataAsync(new Uri(string.Format("imap://{0}/INBOX/;UID=1", server.HostPort)));

            if (!waitHandle.WaitOne(5000))
              Assert.Fail("timed out");
              }
            }
              }
        }
Exemplo n.º 17
0
        public static void    GetQQStatusImage (string qq, Action<BitmapImage> succeed)
        {
            if(string.IsNullOrEmpty(qq))
                return;
            lock (LockObject)
            {
                lock(QqImages)
                {
                    BitmapImage img = null;
                    if(QqImages.TryGetValue(qq,out img))
                    {
                        succeed(img);
                        return   ;
                    }
                }
                bool ext = TakeQqImageTasks.Select(a => a.QQ).Contains(qq);

                var task = new GetQQImageTask
                {
                    QQ = qq,
                    Succeed = succeed
                };
                TakeQqImageTasks.Add(task);
                if(ext == false)
                {
                    string url = string.Format("tencent://message/?uin={0}", qq);
                    Task.Run(() =>
                    {
                        try
                        {
                            var net = new WebClient();
                            net.DownloadDataAsync(new Uri(url));
                            Debug.WriteLine("提取image:" + qq );
                            net.DownloadDataCompleted += (sender, args) =>
                            {
                                if(args.Error != null)
                                    return;
                                var bit = new BitmapImage();
                                bit.BeginInit();
                        
                                bit.StreamSource = new MemoryStream(args.Result);
                                bit.EndInit();
                                lock(QqImages)
                                {
                                    QqImages.Add(qq,bit);
                                }
                                TakeQqImageTasks.ForEach(a =>
                                {
                                    a.Succeed(bit); 
                                });
                            };
                        } catch(Exception e)
                        { 
                        }
                        
                    });
                   
                }
            }
        }
Exemplo n.º 18
0
        public void MakeRequest(Uri url, Action <HttpResponse> onSuccess, Action <ApiException> onError)
        {
            var client = new HttpClient();

            //client.Headers[HttpRequestHeader.UserAgent] = "Stacky";
#if !SILVERLIGHT
            client.Headers[HttpRequestHeader.AcceptEncoding] = "gzip";
            client.Encoding = Encoding.UTF8;
            client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
            client.DownloadDataAsync(url, new RequestContext {
                Url = url, OnSuccess = onSuccess, OnError = onError
            });
#else
#if WINDOWSPHONE
            client.OpenReadAsync(url, new RequestContext {
                Url = url, OnSuccess = onSuccess, OnError = onError
            });
            client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
#else
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
            client.DownloadStringAsync(url, new RequestContext {
                Url = url, OnSuccess = onSuccess, OnError = onError
            });
#endif
#endif
        }
Exemplo n.º 19
0
        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;

                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);
            }
        }
Exemplo n.º 20
0
        public void UpdateRow(CategoryEntity category, Single fontSize, SizeF imageViewSize)
        {
            LabelView.Text = category.Name;
            
            if (category.Picture != null && category.Picture != "BsonNull")
            {
                try
                {
                    var webClient = new WebClient();
                    webClient.DownloadDataCompleted += (s, e) =>
                    {
                        var bytes = e.Result; // get the downloaded data
                            ImageView.Image = ImageHandler.BytesToImage(bytes); // convert the data to an actual image
                    };
                    webClient.DownloadDataAsync(new Uri(category.Picture));
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Something went wrong loading image for cell..." + ex.Message);
                }
                
            }
     
            LabelView.Font = UIFont.FromName("HelveticaNeue-Bold", fontSize);

            ImageView.Frame = new RectangleF(0, 0, imageViewSize.Width, imageViewSize.Height);
            // Position category label below image
            LabelView.Frame = new RectangleF(0, (float) ImageView.Frame.Bottom+60, imageViewSize.Width, (float) (ContentView.Frame.Height - ImageView.Frame.Bottom));
        }
Exemplo n.º 21
0
        public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
            var cell = (RestaurantCell)tableView.DequeueReusableCell(CellIdentifier);
            var item = this.viewModel.Resturants[indexPath.Row];

            if (cell == null)
            {
                cell = RestaurantCell.Create();
            }

            cell.item = item;

            // Load logo
            var webClient = new WebClient();
            webClient.DownloadDataCompleted += (sender, e) =>
            {
                var img = UIImage.LoadFromData(NSData.FromArray(e.Result));

                var image = new UIImageView(img) { Frame = cell.Logo.Bounds };
                image.ContentMode = UIViewContentMode.ScaleAspectFit;
                cell.Logo.AddSubview(image);
            };
            webClient.DownloadDataAsync(new Uri(item.Logo[0].StandardResolutionUrl));

            return cell;
        }
Exemplo n.º 22
0
		protected void HandleTouchUpInside (object sender, System.EventArgs ea)
		{
			var webClient = new WebClient();
			webClient.DownloadDataCompleted += (s, e) => {
				var bytes = e.Result;
				string documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal);	
				string localFilename = "downloaded.png";
				string localPath = Path.Combine (documentsPath, localFilename);
				
				Console.WriteLine("localPath:"+localPath);

				File.WriteAllBytes (localPath, bytes);
	
				// IMPORTANT: this is a background thread, so any interaction with
				// UI controls must be done via the MainThread
				InvokeOnMainThread (() => {
					
					imageView.Image = UIImage.FromFile (localPath);

					new UIAlertView ("Done"
						, "Image downloaded and saved."
						, null
						, "OK"
						, null).Show();
				});
			};
			
			var url = new Uri ("http://xamarin.com/resources/design/home/devices.png");
			webClient.DownloadDataAsync (url);
		}
        /// <summary>
        ///     下载影视资源页完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void Urldown_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null || e.Result.Length <= 0 || e.Cancelled)
            {
                return;
            }
            string resultstr = e.Result;
            if (string.IsNullOrEmpty(resultstr)) return;

            // 解析影视资料页的数据并生成模型
            LiuXingData tag = SearchData.JieXiSearchData(resultstr);
            if (tag == null) return;
            tag.Drl = SearchUrl.GetThisUrl(resultstr);
            if (tag.Drl == null || tag.Drl.Count <= 0) return;
            if (string.IsNullOrEmpty(tag.Img)) return;
            using (
                var imgdown = new WebClient
                    {
                        Encoding = Encoding.UTF8,
                        Proxy = PublicStatic.MyProxy
                    })
            {
                imgdown.DownloadDataAsync(new Uri(tag.Img), tag);
                imgdown.DownloadDataCompleted += SearchImg.Imgdown_DownloadDataCompleted;
            }
        }
Exemplo n.º 24
0
        public static void DeserializeAsync(Uri webURI, bool useRandomGroupedProtocolIfAvailable, Action<Protocol> callback)
        {
            try
            {
                WebClient downloadClient = new WebClient();

                #if __ANDROID__ || __IOS__
                downloadClient.DownloadDataCompleted += (o, e) =>
                {
                    DeserializeAsync(e.Result, useRandomGroupedProtocolIfAvailable, callback);
                };
                #elif WINDOWS_PHONE
                // TODO:  Read bytes and display.
                #else
                #error "Unrecognized platform."
                #endif

                downloadClient.DownloadDataAsync(webURI);
            }
            catch (Exception ex)
            {
                string errorMessage = "Failed to download protocol from URI \"" + webURI + "\":  " + ex.Message + ". If this is an HTTPS URI, make sure the server's certificate is valid.";
                SensusServiceHelper.Get().Logger.Log(errorMessage, LoggingLevel.Normal, typeof(Protocol));
                SensusServiceHelper.Get().FlashNotificationAsync(errorMessage);
            }
        }
Exemplo n.º 25
0
 public void Initialize()
 {
     WebClient wc = new WebClient() {Proxy = null};
     wc.DownloadProgressChanged += WcOnDownloadProgressChanged;
     wc.DownloadDataCompleted += OnDownloadCompleted;
     wc.DownloadDataAsync(new Uri(DownloadUrl));
 }
Exemplo n.º 26
0
        private void Download()
        {
            int totalSize = 0;
            foreach (FileItem fi in _files)
            {
                totalSize += fi.FileSize;
            }

            progressBar1.Maximum = totalSize;
            progressBar1.Value = 0;

            using (WebClient downloader = new WebClient())
            {
                ServicePointManager.ServerCertificateValidationCallback =
                     ((sender, certificate, chain, sslPolicyErrors) => true);
                downloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloader_DownloadProgressChanged);
                downloader.DownloadDataCompleted += new DownloadDataCompletedEventHandler(downloader_DownloadDataCompleted);

                foreach (FileItem fileInfo in _files)
                {
                    string downloadUrl = Constants.Server_Download_Directory + "/" + fileInfo.FileName + "?t=" + Guid.NewGuid().ToString("N");
                    Uri uri = new Uri(downloadUrl);
                    downloader.DownloadDataAsync(uri, fileInfo);
                }
            }
        }
Exemplo n.º 27
0
        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            ImageView imageView = new ImageView(mContext);
            imageView.SetScaleType(ImageView.ScaleType.CenterCrop);
            imageView.LayoutParameters = (new GridView.LayoutParams(250, 250));

            if (Categories[position].Picture != null)
            {
                var webClient = new WebClient();
                webClient.DownloadDataCompleted += (s, e) =>
                {
                    try
                    {
                        var bytes = e.Result; // get the downloaded data
                        
                        imageView.SetImageBitmap(ImageHandler.BytesToImage(bytes));  // convert the data to an actual image
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Something went wrong loading image for cell..." + ex.Message);
                    }

                };
                webClient.DownloadDataAsync(new Uri(Categories[position].Picture));
            }

            return imageView;
        }
Exemplo n.º 28
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            View view = inflater.Inflate(Resource.Layout.InspectUser, container, false);

            //mProfilePic = view.FindViewById<ProfilePictureView>(Resource.Id.profilePic);
            mProfilePic = view.FindViewById<RoundedImageView>(Resource.Id.profilePic);
            mNameText = view.FindViewById<TextView>(Resource.Id.nameTxt);
            addUserAsFriendBtn = view.FindViewById<Button>(Resource.Id.addUserAsFriendsBtn);
            trackUserBtn = view.FindViewById<Button>(Resource.Id.trackUserBtn);

            topLeftToolbarButton = Activity.FindViewById<Button>(Resource.Id.topToolbarButtonLeft);
            topRightToolbarButton = Activity.FindViewById<Button>(Resource.Id.topToolbarButtonRight);
            topLeftToolbarImageButton = Activity.FindViewById<ImageButton>(Resource.Id.topToolbarImageButtonLeft);
            topRightToolbarImageButton = Activity.FindViewById<ImageButton>(Resource.Id.topToolbarImageButtonRight);

            topLeftToolbarButton.Visibility = ViewStates.Gone;
            topLeftToolbarImageButton.Visibility = ViewStates.Gone;
            topRightToolbarButton.Visibility = ViewStates.Gone;
            topRightToolbarImageButton.Visibility = ViewStates.Gone;

            addUserAsFriendBtn.Visibility = ViewStates.Invisible;
            trackUserBtn.Visibility = ViewStates.Invisible;

            //mProfilePic.ProfileId = Profile.CurrentProfile.Id;

            webClient = new WebClient();
            profilePicUri = new Uri("https://graph.facebook.com/"+Profile.CurrentProfile.Id+"/picture?height=500&width=500");
            webClient.DownloadDataAsync(profilePicUri);
            webClient.DownloadDataCompleted += WebClient_DownloadDataCompleted;

            mNameText.Text = Profile.CurrentProfile.Name;

            return view;
        }
Exemplo n.º 29
0
 public void Start()
 {
     var newWebClient = new WebClient {Proxy = null};
     wc = newWebClient;
     newWebClient.DownloadProgressChanged += wc_ProgressChanged;
     newWebClient.DownloadDataCompleted += wc_DownloadDataCompleted;
     newWebClient.DownloadDataAsync(new Uri(Name), this);
 }
Exemplo n.º 30
0
 public void ProcessRequest(HttpContext context)
 {
     cont = context;
     string qs = context.Request.QueryString["tts"];
        WebClient Client = new WebClient ();
        Client.DownloadDataCompleted += Client_DownloadDataCompleted;
     Client.DownloadDataAsync(new Uri("http://translate.google.com/translate_tts?ie=utf-8&tl=en&q="+qs));
 }
Exemplo n.º 31
0
 public void DownloadAsync(Action<byte[]> callback)
 {
     using (var client = new WebClient())
     {
         client.DownloadDataCompleted += (sender, args) => callback(args.Result);
         client.DownloadDataAsync(_uri);
     }
 }
Exemplo n.º 32
0
		public static void DownloadContextAsync(string url, DownloadDataCompletedEventHandler e) {
			using (var webClient = new WebClient {
				Encoding = Encoding.UTF8
			}) {
				webClient.DownloadDataAsync(new Uri(url));
				webClient.DownloadDataCompleted += e;
			}
		}
Exemplo n.º 33
0
 public void detectSnapshotVersion()
 {
     WebClient client = new WebClient();
     client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(mainForm.DownloadProgressChanged);
     client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(snapshot_DownloadDataCompleted);
     mainForm.statusLabel.Text = "Checking for Updates!";
     client.DownloadDataAsync(new Uri("http://mojang.com/feed"));
 }
Exemplo n.º 34
0
        public void RSPEC_WebClient(string address, Uri uriAddress, byte[] data,
                                    NameValueCollection values)
        {
            System.Net.WebClient webclient = new System.Net.WebClient();

            // All of the following are Questionable although there may be false positives if the URI scheme is "ftp" or "file"
            //webclient.Download * (...); // Any method starting with "Download"
            webclient.DownloadData(address);                            // Noncompliant
            webclient.DownloadDataAsync(uriAddress, new object());      // Noncompliant
            webclient.DownloadDataTaskAsync(uriAddress);                // Noncompliant
            webclient.DownloadFile(address, "filename");                // Noncompliant
            webclient.DownloadFileAsync(uriAddress, "filename");        // Noncompliant
            webclient.DownloadFileTaskAsync(address, "filename");       // Noncompliant
            webclient.DownloadString(uriAddress);                       // Noncompliant
            webclient.DownloadStringAsync(uriAddress, new object());    // Noncompliant
            webclient.DownloadStringTaskAsync(address);                 // Noncompliant

            // Should not raise for events
            webclient.DownloadDataCompleted   += Webclient_DownloadDataCompleted;
            webclient.DownloadFileCompleted   += Webclient_DownloadFileCompleted;
            webclient.DownloadProgressChanged -= Webclient_DownloadProgressChanged;
            webclient.DownloadStringCompleted -= Webclient_DownloadStringCompleted;


            //webclient.Open * (...); // Any method starting with "Open"
            webclient.OpenRead(address);
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^   {{Make sure that this http request is sent safely.}}
            webclient.OpenReadAsync(uriAddress, new object());              // Noncompliant
            webclient.OpenReadTaskAsync(address);                           // Noncompliant
            webclient.OpenWrite(address);                                   // Noncompliant
            webclient.OpenWriteAsync(uriAddress, "STOR", new object());     // Noncompliant
            webclient.OpenWriteTaskAsync(address, "POST");                  // Noncompliant

            webclient.OpenReadCompleted  += Webclient_OpenReadCompleted;
            webclient.OpenWriteCompleted += Webclient_OpenWriteCompleted;

            //webclient.Upload * (...); // Any method starting with "Upload"
            webclient.UploadData(address, data);                           // Noncompliant
            webclient.UploadDataAsync(uriAddress, "STOR", data);           // Noncompliant
            webclient.UploadDataTaskAsync(address, "POST", data);          // Noncompliant
            webclient.UploadFile(address, "filename");                     // Noncompliant
            webclient.UploadFileAsync(uriAddress, "filename");             // Noncompliant
            webclient.UploadFileTaskAsync(uriAddress, "POST", "filename"); // Noncompliant
            webclient.UploadString(uriAddress, "data");                    // Noncompliant
            webclient.UploadStringAsync(uriAddress, "data");               // Noncompliant
            webclient.UploadStringTaskAsync(uriAddress, "data");           // Noncompliant
            webclient.UploadValues(address, values);                       // Noncompliant
            webclient.UploadValuesAsync(uriAddress, values);               // Noncompliant
            webclient.UploadValuesTaskAsync(address, "POST", values);
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

            // Should not raise for events
            webclient.UploadDataCompleted   += Webclient_UploadDataCompleted;
            webclient.UploadFileCompleted   += Webclient_UploadFileCompleted;
            webclient.UploadProgressChanged -= Webclient_UploadProgressChanged;
            webclient.UploadStringCompleted -= Webclient_UploadStringCompleted;
            webclient.UploadValuesCompleted -= Webclient_UploadValuesCompleted;
        }
Exemplo n.º 35
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;
        }
Exemplo n.º 36
0
 private static void DownloadAsBytesASync(string url, Action <object, DownloadDataCompletedEventArgs> callback)
 {
     SetCertificate();
     using (var wc = new System.Net.WebClient())
     {
         wc.DownloadDataCompleted += new DownloadDataCompletedEventHandler(callback);
         wc.DownloadDataAsync(new Uri(url));
     }
 }
Exemplo n.º 37
0
        public static bool CheckUpdateStatus()
        {
            bool isUpdate = false;

            System.Threading.ThreadPool.QueueUserWorkItem((s) =>
            {
                //string url = Constants.WpfAutoUpdateUrl + Updater.Instance.CallExeName + "/update.xml";
                string url = Constants.WpfAutoUpdateUrl + "/update.xml";
                var client = new System.Net.WebClient();
                client.DownloadDataCompleted += (x, y) =>
                {
                    MemoryStream stream = null;
                    try
                    {
                        try
                        {
                            stream = new MemoryStream(y.Result);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                        try
                        {
                            XDocument xDoc        = XDocument.Load(stream);
                            UpdateInfo updateInfo = new UpdateInfo();
                            XElement root         = xDoc.Element("UpdateInfo");
                            updateInfo.AppName    = root.Element("AppName").Value;
                            updateInfo.AppVersion = root.Element("AppVersion") == null ||
                                                    string.IsNullOrEmpty(root.Element("AppVersion").Value)
                                ? null
                                : new Version(root.Element("AppVersion").Value);
                            updateInfo.RequiredMinVersion = root.Element("RequiredMinVersion") == null ||
                                                            string.IsNullOrEmpty(root.Element("RequiredMinVersion").Value)
                                ? null
                                : new Version(root.Element("RequiredMinVersion").Value);
                            updateInfo.Desc = root.Element("Desc").Value;
                            updateInfo.MD5  = Guid.NewGuid();

                            stream.Close();
                            isUpdate = Updater.Instance.StartUpdate(updateInfo);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                };
                client.DownloadDataAsync(new Uri(url));
            });
            GC.Collect();
            return(isUpdate);
        }
Exemplo n.º 38
0
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                Permission();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Bạn cần thiết lập quyền ghi tập tin cho thư mục cài đặt trước khi cập nhật phiên bản.\n "
                                + ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Process.Start(Application.StartupPath);
                this.Close();
                return;
            }

            try
            {
                lblStatus.Text = "Đang tìm kiếm bản cập nhật mới";
                this.Update();

                System.Net.WebClient client = new System.Net.WebClient();
                NewVersion = client.DownloadString("http://18.220.41.128/Version.txt");

                var oldVersion = "";
                try
                {
                    oldVersion = System.IO.File.ReadAllText(Application.StartupPath + "\\Version.txt").Replace("\r\n", "");
                }
                catch { }

                if (NewVersion == oldVersion)
                {
                    lblStatus.Text  = "Không có bản cập nhật mới";
                    btn_cancel.Text = "Thoát";
                    return;
                }

                foreach (Process p in Process.GetProcesses())
                {
                    if ((p.ProcessName.ToLower() == "khieunaitocao"))
                    {
                        p.Kill();
                    }
                }


                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                client.DownloadDataCompleted   += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
                client.DownloadDataAsync(new Uri("http://18.220.41.128/Version.zip"));
            }
            catch
            {
                lblStatus.Text  = "Không tìm thấy phiên bản mới";
                btn_cancel.Text = "Thoát";
            }
        }
Exemplo n.º 39
0
        async void GetImageBitmapFromUrl(string url, DownloadDataCompletedEventHandler eventFunc)
        {
            Bitmap img1 = null;

            using (var webClient = new System.Net.WebClient())
            {
                webClient.DownloadDataCompleted += eventFunc;
                webClient.DownloadDataAsync(new Uri(url));
            }
        }
Exemplo n.º 40
0
 void Download()
 {
     try
     {
         using (WebClient c = new System.Net.WebClient())
         {
             c.DownloadProgressChanged += DownloadProgressChanged;
             c.DownloadDataCompleted   += DownloadDataCompleted;
             c.DownloadDataAsync(new Uri(url));
         }
     }
     catch (Exception e)
     {
         Error = e.ToString();
     }
 }
Exemplo n.º 41
0
 void Download()
 {
     try
     {
         using (WebClient c = new System.Net.WebClient())
         {
             ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
             c.DownloadProgressChanged += DownloadProgressChanged;
             c.DownloadDataCompleted   += DownloadDataCompleted;
             c.DownloadDataAsync(new Uri(url));
         }
     }
     catch (Exception e)
     {
         Error = e.ToString();
     }
 }
Exemplo n.º 42
0
        /// <summary>Downloads the resource with the specified URI as a byte array, asynchronously.</summary>
        /// <param name="webClient">The WebClient.</param>
        /// <param name="address">The URI from which to download data.</param>
        /// <returns>A Task that contains the downloaded data.</returns>
        public static Task <byte[]> DownloadDataTask(this WebClient webClient, Uri address)
        {
            TaskCompletionSource <byte[]>     tcs     = new TaskCompletionSource <byte[]>(address);
            DownloadDataCompletedEventHandler handler = null;

            handler = delegate(object sender, DownloadDataCompletedEventArgs e) {
                EAPCommon.HandleCompletion <byte[]>(tcs, e, () => e.Result, delegate {
                    webClient.DownloadDataCompleted -= handler;
                });
            };
            webClient.DownloadDataCompleted += handler;
            try
            {
                webClient.DownloadDataAsync(address, tcs);
            }
            catch (Exception exception)
            {
                webClient.DownloadDataCompleted -= handler;
                tcs.TrySetException(exception);
            }
            return(tcs.Task);
        }
Exemplo n.º 43
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            SetContentView(Resource.Layout.openCarLayout);
            base.OnCreate(savedInstanceState);
            carId = Intent.GetStringExtra("ID");

            carInfo_result info = new carInfo_result();

            info.get_from_cloud("https://carshareserver.azurewebsites.net/api/getCarDetails?vehicle_id=" + carId);
            carTotalInfo totalInfo = info.getInfo();

            IMG = totalInfo.img;

            CheckBt();
            bluetoothDeviceReceiver = new BluetoothDeviceReceiver(MAC_ADDRESS, this);
            RegisterReceiver(bluetoothDeviceReceiver, new IntentFilter(BluetoothDevice.ActionFound));

            openCarButton = FindViewById <Button>(Resource.Id.openCarButton);
            var gradientDrawable = openCarButton.Background.Current as GradientDrawable;

            gradientDrawable.SetColor(Color.Gray);
            openCarButton.Click  += tryOpenCar;
            openCarButton.Enabled = false;

            TextView lisence = FindViewById <TextView>(Resource.Id.openCarLicense);

            lisence.Text = carId;
            async void GetImageBitmapFromUrl(string url, DownloadDataCompletedEventHandler eventFunc)
            {
                Bitmap img1 = null;

                using (var webClient = new System.Net.WebClient())
                {
                    webClient.DownloadDataCompleted += eventFunc;
                    webClient.DownloadDataAsync(new Uri(url));
                }
            }

            if (IMG != "")
            {
                GetImageBitmapFromUrl(IMG, loadCarImage);
                void loadCarImage(object sender, DownloadDataCompletedEventArgs e)
                {
                    byte[] raw  = e.Result;
                    Bitmap img1 = BitmapFactory.DecodeByteArray(raw, 0, raw.Length);

                    if (img1 != null)
                    {
                        ImageView imagen = FindViewById <ImageView>(Resource.Id.openCarImg);
                        imagen.SetImageBitmap(img1);

                        //Calculate image size
                        double ratio = (double)img1.Height / (double)img1.Width;
                        FindViewById <RelativeLayout>(Resource.Id.openCarloadingPanel).Visibility = ViewStates.Gone;
                        imagen.LayoutParameters.Height = (int)((double)Resources.DisplayMetrics.WidthPixels * ratio);
                    }
                }
            }
            else
            {
                FindViewById <RelativeLayout>(Resource.Id.openCarloadingPanel).Visibility = ViewStates.Gone;
            }


            bool started = mBluetoothAdapter.StartDiscovery();

            System.Console.WriteLine("is scan startd: " + started);
            //Connect();
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.handleReqLayout);
            carId     = Intent.GetStringExtra("ID");
            renter_id = Intent.GetStringExtra("renter_id");


            user   user       = new user();
            string login_hash = Preferences.Get("login_hash", "1");

            user.get_from_cloud(renter_id, login_hash);

            approve   = FindViewById <Button>(Resource.Id.approveReqButton);
            decline   = FindViewById <Button>(Resource.Id.declineReqButton);
            carImage  = FindViewById <ImageView>(Resource.Id.handleRequstImg);
            lisence   = FindViewById <TextView>(Resource.Id.handelReqLicense);
            userEmail = FindViewById <TextView>(Resource.Id.handleReqUserEmail);
            username  = FindViewById <TextView>(Resource.Id.handleReqUserName);

            username.Text  = user.first_name + " " + user.last_name;
            userEmail.Text = user.email;

            approve.Click += approveAction;
            decline.Click += declineAction;
            carInfo_result info = new carInfo_result();

            info.get_from_cloud("https://carshareserver.azurewebsites.net/api/getCarDetails?vehicle_id=" + carId);
            carTotalInfo totalInfo = info.getInfo();

            IMG          = totalInfo.img;
            lisence.Text = totalInfo.id;
            async void GetImageBitmapFromUrl(string url, DownloadDataCompletedEventHandler eventFunc)
            {
                Bitmap img1 = null;

                using (var webClient = new System.Net.WebClient())
                {
                    webClient.DownloadDataCompleted += eventFunc;
                    webClient.DownloadDataAsync(new Uri(url));
                }
            }

            if (IMG != "")
            {
                GetImageBitmapFromUrl(IMG, loadCarImage);

                void loadCarImage(object sender, DownloadDataCompletedEventArgs e)
                {
                    byte[] raw  = e.Result;
                    Bitmap img1 = BitmapFactory.DecodeByteArray(raw, 0, raw.Length);

                    if (img1 != null)
                    {
                        ImageView imagen = FindViewById <ImageView>(Resource.Id.handleRequstImg);
                        imagen.SetImageBitmap(img1);

                        //Calculate image size
                        double ratio = (double)img1.Height / (double)img1.Width;
                        FindViewById <RelativeLayout>(Resource.Id.handelReqLoadingPanel).Visibility = ViewStates.Gone;
                        imagen.LayoutParameters.Height = (int)((double)Resources.DisplayMetrics.WidthPixels * ratio);
                    }
                }
            }
            else
            {
                FindViewById <RelativeLayout>(Resource.Id.handelReqLoadingPanel).Visibility = ViewStates.Gone;
            }
        }
Exemplo n.º 45
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            carId = Intent.GetStringExtra("ID");
            SetContentView(Resource.Layout.carInfoLayout);
            GridLayout carModeGridLayout = FindViewById <GridLayout>(Resource.Id.gridLayout1);

            TextView carModelView      = FindViewById <TextView>(Resource.Id.carInfoModel);
            TextView carProductionView = FindViewById <TextView>(Resource.Id.carInfoProduction);
            TextView carLicenseView    = FindViewById <TextView>(Resource.Id.carInfoLicense);
            TextView carModeView       = FindViewById <TextView>(Resource.Id.carInfoMode);
            TextView carUserView       = FindViewById <TextView>(Resource.Id.carInfoUser);
            TextView carUserEmailView  = FindViewById <TextView>(Resource.Id.carInfoUserEmail);
            TextView carInfoReview     = FindViewById <TextView>(Resource.Id.carInfoUserReview);

            requestCarButton        = FindViewById <Button>(Resource.Id.requestCarButton);
            requestCarButton.Click += requestCar;
            Button viewReviews = FindViewById <Button>(Resource.Id.carInfoViewReviews);

            viewReviews.Click += viewFunc;
            carInfo_result info = new carInfo_result();

            info.get_from_cloud("https://carshareserver.azurewebsites.net/api/getCarDetails?vehicle_id=" + carId);
            carTotalInfo totalInfo = info.getInfo();

            carModelView.Text      = totalInfo.Manufacturer + " " + totalInfo.model;
            carProductionView.Text = totalInfo.year;
            carLicenseView.Text    = carId;
            if (totalInfo.mode)
            {
                carModeView.Text = "Automatic";
            }
            else
            {
                carModeView.Text = "Manual";
            }

            user carOwner = totalInfo.User;

            Preferences.Set("reviewee", carOwner.id);
            carUserView.Text      = carOwner.first_name + " " + carOwner.last_name;
            carUserEmailView.Text = carOwner.email;
            async void GetImageBitmapFromUrl(string url, DownloadDataCompletedEventHandler eventFunc)
            {
                Bitmap img1 = null;

                using (var webClient = new System.Net.WebClient())
                {
                    webClient.DownloadDataCompleted += eventFunc;
                    webClient.DownloadDataAsync(new Uri(url));
                }
            }

            if (carOwner.img != "")
            {
                GetImageBitmapFromUrl("https://carshareserver.azurewebsites.net/api/getUserImage?user_id=" + carOwner.id, loadUserImage);

                void loadUserImage(object sender, DownloadDataCompletedEventArgs e)
                {
                    byte[] raw  = e.Result;
                    Bitmap img1 = BitmapFactory.DecodeByteArray(raw, 0, raw.Length);

                    if (img1 != null)
                    {
                        ImageView userImage = FindViewById <ImageView>(Resource.Id.userImg);
                        userImage.SetImageBitmap(img1);
                    }
                }
            }
            if (totalInfo.img != "")
            {
                imgAdress = totalInfo.img;
                GetImageBitmapFromUrl(imgAdress, loadCarImage);

                void loadCarImage(object sender, DownloadDataCompletedEventArgs e)
                {
                    byte[] raw  = e.Result;
                    Bitmap img1 = BitmapFactory.DecodeByteArray(raw, 0, raw.Length);

                    if (img1 != null)
                    {
                        ImageView imagen = FindViewById <ImageView>(Resource.Id.carInfoImg);
                        imagen.SetImageBitmap(img1);

                        //Calculate image size
                        double ratio = (double)img1.Height / (double)img1.Width;
                        FindViewById <RelativeLayout>(Resource.Id.carInfoLoadingPanel).Visibility = ViewStates.Gone;
                        imagen.LayoutParameters.Height = (int)((double)Resources.DisplayMetrics.WidthPixels * ratio);
                    }
                }
            }
            else
            {
                FindViewById <RelativeLayout>(Resource.Id.carInfoLoadingPanel).Visibility = ViewStates.Gone;
            }
            reviewee = carOwner.id;
            string user_id    = Preferences.Get("user_id", "");
            string login_hash = Preferences.Get("login_hash", "");
            string address    = "https://carshareserver.azurewebsites.net/api/getReviews?reviewee_id=" + reviewee + "&login_hash=" + login_hash + "&user_id=" + user_id;

            reviewInfo.get_from_cloud(address);
            int stauts = reviewInfo.getReviews().status;

            if (stauts == -1)
            {
                carInfoReview.Text = "N/A";
            }
            else
            {
                if (reviewInfo.getReviews().avg_rate == -1)
                {
                    carInfoReview.Text = "N/A";
                }
                else
                {
                    carInfoReview.Text = reviewInfo.getReviews().avg_rate.ToString();
                }
            }
        }