OpenReadAsync() публичный Метод

public OpenReadAsync ( System address ) : void
address System
Результат void
Пример #1
0
        private void getpage(string inputurl)
        {
            var webClient = new WebClient();

            IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;

            if (appSettings.Contains("BService") && !((bool)appSettings["BService"]))
            {
                webClient.OpenReadAsync(new Uri("http://v.gd/create.php?format=simple&callback=myfunction&url=" + inputurl + "&logstats=1" + DateTime.Now));
            }
            else webClient.OpenReadAsync(new Uri("http://is.gd/create.php?format=simple&callback=myfunction&url=" + inputurl + "&logstats=1" + DateTime.Now));
                
            webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadComplete);
        }
Пример #2
0
        public void doDealList(string cityid)
        {
            var appStoreage = IsolatedStorageFile.GetUserStoreForApplication();
            var filename = string.Format("deals_{0}.xml", cityid);

            if (appStoreage.FileExists(filename))
            {

                using (var file = appStoreage.OpenFile(filename, FileMode.Open, FileAccess.Read))
                {

                    StreamReader sr = new StreamReader(file);

                    xml = XElement.Load(sr);
                    myList.ItemsSource = praseXML(xml);

                    this.cacheTime.Text = "[缓存时间:" + appStoreage.GetCreationTime(filename).ToString() + "]";
                }

                this.PageTitle.Text = myCity.Name + "团购";
            }
            else
            {
                WebClient client = new WebClient();
                Uri uri = new Uri(String.Format("http://www.meituan.com/api/v2/{0}/deals", cityid), UriKind.Absolute);
                client.OpenReadAsync(uri, cityid);
                client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
            }
        }
        //public void Save(string imageUrl)
        //{
        //    ThreadPool.QueueUserWorkItem(GetImage, imageUrl);
        //}
        private void Download(string imageUrl, string imageName, Action<BitmapImage> callBack, string imageSaveName)
        {
            var imageUri = new Uri(string.Format(imageUrl, imageName));

            var client = new WebClient();
            client.OpenReadCompleted += (s, e) =>
            {
                try
                {
                    var streamResourseInfo = new StreamResourceInfo(e.Result, null);
                    var streamReader = new StreamReader(streamResourseInfo.Stream);
                    byte[] imageBytes;
                    using (var binaryReader = new BinaryReader(streamReader.BaseStream))
                    {
                        imageBytes = binaryReader.ReadBytes((int)streamReader.BaseStream.Length);
                    }

                    string name = imageSaveName ?? imageName;
                    using (var stream = _isolatedStorageFile.CreateFile(name))
                    {
                        stream.Write(imageBytes, 0, imageBytes.Length);
                        var image = new BitmapImage();
                        image.SetSource(stream);
                        callBack.Invoke(image);
                    }
                }
                catch (Exception ex)
                {
                    // Let it fail if not something catastrophic
                    if (!(ex is WebException))
                        throw;
                }
            };
            client.OpenReadAsync(imageUri, client);
        }
        public static byte[] DownloadData(this WebClient webClient, Uri uri)
        {
            byte[] data = null;
            try
            {
                var manualReset = new ManualResetEvent(false);
                var client = new WebClient();

                client.OpenReadCompleted += (o, e) =>
                {
                    if (e.Error == null)
                    {
                        data = e.Result.ReadToEnd();
                    }
                    manualReset.Set();
                };
                client.OpenReadAsync(uri);

                manualReset.WaitOne(TIMEOUT);
            }
            catch (WebException e)
            {
                //Do nothing, return null
            }
            return data;
        } 
        private void MyMap_MouseClick(object sender, ESRI.ArcGIS.Client.Map.MouseEventArgs e)
        {
            MapPoint geographicPoint = _mercator.ToGeographic(e.MapPoint) as MapPoint;

            string SOEurl = "http://sampleserver4.arcgisonline.com/ArcGIS/rest/services/Elevation/ESRI_Elevation_World/MapServer/exts/ElevationsSOE/ElevationLayers/1/GetElevationAtLonLat";
            SOEurl += string.Format(System.Globalization.CultureInfo.InvariantCulture, "?lon={0}&lat={1}&f=json", geographicPoint.X, geographicPoint.Y);

            WebClient webClient = new WebClient();

            webClient.OpenReadCompleted += (s, a) =>
            {
                var sr = new StreamReader(a.Result);
                string str = sr.ReadToEnd();

                JObject jsonResponse = JObject.Parse(str);
                double elevation = (double)jsonResponse["elevation"];
                a.Result.Close();

                MyInfoWindow.Anchor = e.MapPoint;
                MyInfoWindow.Content = string.Format("Elevation: {0} meters", elevation.ToString("0"));
                MyInfoWindow.IsOpen = true;
            };

            webClient.OpenReadAsync(new Uri(SOEurl));
        }
Пример #6
0
        private IObservable<string> detect(string text)
        {
            var subject = new AsyncSubject<string>();
            string detectUri = String.Format(GetDetectUri(text), appId, HttpUtility.HtmlEncode(text));

            var wc = new WebClient();
            wc.OpenReadCompleted += new OpenReadCompletedEventHandler((obj, args) =>
            {
                if (args.Error != null)
                {
                    subject.OnError(args.Error);
                }
                else
                {
                    if (!args.Cancelled)
                    {
                        var xdoc = XDocument.Load(args.Result);
                        subject.OnNext(xdoc.Root.Value);
                    }
                    subject.OnCompleted();
                }
            });
            wc.OpenReadAsync(new Uri(detectUri));
            return subject;
        }
Пример #7
0
 public static void GetRssFromTutBy(Object stateInfo)
 {
     Uri serviceUri = new Uri("http://news.tut.by/rss/index.rss");
     WebClient downloader = new WebClient();
     downloader.OpenReadCompleted += new OpenReadCompletedEventHandler(downloader_OpenReadCompleted);
     downloader.OpenReadAsync(serviceUri);
 }
Пример #8
0
        private static void CacheImage(object input)
        {
            // extract the url and BitmapImage from our intput object
            var items = (KeyValuePair<string, BitmapImage>)input;
            var url = items.Key;
            var image = items.Value;

            var cacheFile = SetName(items.Key);

            var waitHandle = new AutoResetEvent(false);
            var fileNameAndWaitHandle = new KeyValuePair<string, AutoResetEvent>(cacheFile, waitHandle);

            var wc = new WebClient();
            wc.OpenReadCompleted += OpenReadCompleted;
            // start the caching call (web async)
            wc.OpenReadAsync(new Uri(url), fileNameAndWaitHandle);

            // wait for the file to be saved, or timeout after 5 seconds
            waitHandle.WaitOne(5000);

          

            if (s.FileExists(cacheFile))
            {
                // ok, our file now exists! set the image source on the UI thread
                Deployment.Current.Dispatcher.BeginInvoke(() => image.SetSource(s.StreamFileFromIsoStore(cacheFile)));
            }

        }
Пример #9
0
 /// <summary>
 /// Gets current login user id and user's member groups
 /// </summary>
 public void GetUserLoginIdAndMemberGroups()
 {
     string uriString = Constants.InitParams.UserLoginIdHelperUrl(mainPage);
     WebClient wcUserLogin = new WebClient();
     wcUserLogin.OpenReadCompleted += new OpenReadCompletedEventHandler(wcUserLogin_OpenReadCompleted);
     wcUserLogin.OpenReadAsync(new Uri(uriString));
 }
        private void ImageResultLoadedCallback(IAsyncResult ar)
        {
            var imageQuery = (DataServiceQuery<Bing.ImageResult>)ar.AsyncState;
            var enumerableImages = imageQuery.EndExecute(ar);
            var imagesList = enumerableImages.ToList();

            if (imagesList.Count == 0)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("No results");
                });

                return;
            }

            RowNow = 0;
            ColumnNow = 0;
            foreach (var image in imagesList)
            {
                WebClient wc = new WebClient();
                int cs = currentSearch;
                wc.OpenReadCompleted += (s, args) =>
                {
                    wc_OpenReadCompleted(s, args, cs);
                };

                wc.OpenReadAsync(new Uri(image.MediaUrl), wc);
            }
        }
Пример #11
0
        private void OnBrowserLoadComple(object sender, NavigationEventArgs e)
        {
            string result = browser.Source.ToString();

            if (result.IndexOf("access_token=") != -1)
            {

                result = result.Replace("http://api.vkontakte.ru/blank.html#", "");

                string[] reqVars = result.Split('&');

                accessToken = reqVars[0].Replace("access_token=", "");
                expiresIn = reqVars[1].Replace("expires_in=", "");
                userId = reqVars[2].Replace("user_id=", "");

                AuthContainer.Visibility = Visibility.Hidden;
                ContentContainer.Visibility = Visibility.Visible;

                Uri getAudioUri = new Uri("https://api.vk.com/method/audio.get.xml?user_id=" + userId + "&v=5.24&access_token=" + accessToken);

                WebClient client = new WebClient();
                client.OpenReadCompleted += OnOpenReadComplete;
                client.OpenReadAsync(getAudioUri);

            }
            else
            {

            }

            //access_token=ec337e46e465f09ed764d78e9cffcc2e797813e37090517872c478932fd9931b3cb449cbca7cfdebc2d7b&expires_in=86400&user_id=64296155
        }
Пример #12
0
 public static void StartDownloadImagefromServer(string imgURL)
 {
     WebClient client = new WebClient();
     client.OpenReadCompleted -= new OpenReadCompletedEventHandler(client_OpenReadCompleted);
     client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
     client.OpenReadAsync(new Uri(imgURL, UriKind.Absolute));
 }
        private void LoadMapButton_Click(object sender, RoutedEventArgs e)
        {
            WebClient webClient = new WebClient();
            string uri = string.Format("http://dev.virtualearth.net/REST/v1/Imagery/Metadata/Aerial?supressStatus=true&key={0}", BingKeyTextBox.Text);

            webClient.OpenReadCompleted += (s, a) =>
            {
                if (a.Error == null)
                {
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(BingAuthentication));
                    BingAuthentication bingAuthentication = serializer.ReadObject(a.Result) as BingAuthentication;
                    a.Result.Close();

                    if (bingAuthentication.authenticationResultCode == "ValidCredentials")
                    {
                        ESRI.ArcGIS.Client.Bing.TileLayer tileLayer = new TileLayer()
                        {
                            ID = "BingLayer",
                            LayerStyle = TileLayer.LayerType.Road,
                            ServerType = ServerType.Production,
                            Token = BingKeyTextBox.Text
                        };

                        MyMap.Layers.Insert(0, tileLayer);

                        BingKeyGrid.Visibility = System.Windows.Visibility.Collapsed;
                        InvalidBingKeyTextBlock.Visibility = System.Windows.Visibility.Collapsed;
                    }
                    else InvalidBingKeyTextBlock.Visibility = System.Windows.Visibility.Visible;
                }
                else InvalidBingKeyTextBlock.Visibility = System.Windows.Visibility.Visible;
            };

            webClient.OpenReadAsync(new System.Uri(uri));
        }
        public static void downloadBackground()
        {
            WebClient client = new System.Net.WebClient();

            client.OpenReadCompleted += new System.Net.OpenReadCompletedEventHandler(client_OpenReadCompleted);
            client.OpenReadAsync(new Uri("http://appserver.m.bing.net/BackgroundImageService/TodayImageService.svc/GetTodayImage?dateOffset=-0&urlEncodeHeaders=true&osName=wince&osVersion=7.10&orientation=480x800&mkt=en-US&deviceName=donttreadonme&AppId=homebrew&UserId=rules", UriKind.Absolute));
        }
Пример #15
0
        private void CommandeAnnales_Tap(object sender, GestureEventArgs e)
        {
            button1.Visibility = Visibility.Collapsed;
            loginCommande.Visibility = Visibility.Collapsed;
            TexteAnnales.Visibility = Visibility.Visible;
            TexteAnnales.Text = "Envoi de la commande...";

            if (panier.Count == 0 || panier.Count > 8)
            {
                TexteAnnales.Text = "Choisissez entre 1 et 8 UVs.";
                Perform(() => finCommande(), 2000);
                return;
            }

            var client = new WebClient();
            var texte = "login="******"&annales=";
            int i = 0;
            foreach (string nom in panier)
            {
                if (i > 0)
                {
                    texte += ",";
                }
                texte += nom;
                i++;
            }
            //client.UploadStringCompleted += new UploadStringCompletedEventHandler(handlerCommande);
            client.OpenReadCompleted += new OpenReadCompletedEventHandler(handlerCommande);
            client.OpenReadAsync(new Uri("http://assos.utc.fr/polar/annales/json?" + texte));
            //client.UploadStringAsync(new Uri("http://assos.utc.fr/polar/annales/borne?commander"), texte);
        }
Пример #16
0
 public void StartRetrieval()
 {
     mainPage.WorkBeingDone(true);
     webClient = new WebClient();
     webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(WebClientOpenReadCompleted);
     webClient.OpenReadAsync(new Uri(NCSU_RSS_FEED_URLS[feedIndex]));
 }
Пример #17
0
        private void btnGet_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Uri uri = null;

            try{ uri = new System.Uri(host.UI.tbUri.Text); }
            catch (Exception) { MessageBox.Show("Bad URI format!"); return; }

            if (m_memIco != null)
            {
                m_memIco.Close();
                m_memIco = null;
            }

            host.UI.icoLst.Items.Clear();
            host.UI.imgPalette.Visibility = System.Windows.Visibility.Collapsed;
            host.UI.imgIcon.Visibility    = System.Windows.Visibility.Collapsed;

            uIco = uri;
            myLoad();

            System.Net.WebClient client = new System.Net.WebClient();
            client.OpenReadCompleted += new System.Net.OpenReadCompletedEventHandler(client_OpenReadCompleted);

            client.OpenReadAsync(uIco);

            host.UI.prsBar.Visibility = System.Windows.Visibility.Visible;
        }
        private void LoadMapButton_Click(object sender, RoutedEventArgs e)
        {
            WebClient webClient = new WebClient();
            string uri = string.Format("http://dev.virtualearth.net/REST/v1/Imagery/Metadata/Aerial?supressStatus=true&key={0}", BingKeyTextBox.Text);

            webClient.OpenReadCompleted += (s, a) =>
            {
                if (a.Error == null)
                {
                    JsonValue jsonResponse = JsonObject.Load(a.Result);
                    string authenticationResult = jsonResponse["authenticationResultCode"];
                    a.Result.Close();

                    BingKeyGrid.Visibility = System.Windows.Visibility.Collapsed;
                    InvalidBingKeyTextBlock.Visibility = System.Windows.Visibility.Collapsed;

                    if (authenticationResult == "ValidCredentials")
                    {
                        Document webMap = new Document();
                        webMap.BingToken = BingKeyTextBox.Text;
                        webMap.GetMapCompleted += (s1, e1) =>
                        {
                            if (e1.Error == null)
                                LayoutRoot.Children.Add(e1.Map);
                        };

                        webMap.GetMapAsync("75e222ec54b244a5b73aeef40ce76adc");
                    }
                    else InvalidBingKeyTextBlock.Visibility = System.Windows.Visibility.Visible;
                }
                else InvalidBingKeyTextBlock.Visibility = System.Windows.Visibility.Visible;
            };

            webClient.OpenReadAsync(new System.Uri(uri));
        }
Пример #19
0
        public void Call(string args)
        {
            CdcOptions options = JsonHelper.Deserialize<CdcOptions>(args);

            var url = new Uri(options.Path, UriKind.Absolute);

            var webClient = new WebClient();

            webClient.OpenReadCompleted += (s, e) =>
            {
                if (e.Error != null)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error"));
                    return;
                }

                //Stream -> string
                var sr = new StreamReader(e.Result);
                var result = sr.ReadToEnd();

                DispatchCommandResult(
                    new PluginResult(PluginResult.Status.OK, result));
            };

            webClient.OpenReadAsync(url, url);

        }
        public DocumentExplorer()
        {
            InitializeComponent();

            var documentsUri = new Uri(HtmlPage.Document.DocumentUri, "Documents/Documents.xml");

            var client = new WebClient();
            client.OpenReadCompleted += (o, e) => {
                if (!e.Cancelled) {
                    if (e.Error != null) {
                        ErrorWindow.ShowError(e.Error);
                    }
                    else {
                        using (e.Result) {
                            var doc = XDocument.Load(e.Result, LoadOptions.None);
                            var docs = from document in doc.Descendants("Document")
                                       select new DocumentInfo() {
                                           Name = (string)document.Attribute("Name"),
                                           Description= (string)document.Attribute("Description"),
                                           OriginalLocation = new Uri(documentsUri, (string)document.Attribute("Name")),
                                           XpsLocation = new Uri(documentsUri, (string)document.Attribute("XpsLocation"))
                                       };

                            this.documents.ItemsSource = docs;
                        }
                    }
                }
            };

            client.OpenReadAsync(documentsUri);
        }
Пример #21
0
 public static void FetchPythonExtensions() {
     WebClient wc = new WebClient();
     var index = 2; // Python 
     var uri = Package.LanguageExtensionUris[index];
     wc.OpenReadCompleted += new OpenReadCompletedEventHandler(FetchPythonExtensionsCompleted);
     wc.OpenReadAsync(new Uri(uri));
 }
 public void Download()
 {
     var client = new WebClient();
     var uri = new Uri("http://localhost/MediaInTheCloud.Host/Home/GetServerItems");
     client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
     client.OpenReadAsync(uri);
 }
Пример #23
0
 public static void FetchDLR(Action downloadsCompleted) {
     _downloadsCompleted = downloadsCompleted;
     WebClient wc = new WebClient(); 
     string sRequest = Package.LanguageExtensionUris[0]; // DLR 
     wc.OpenReadCompleted += new OpenReadCompletedEventHandler(FetchDLRCompleted);
     wc.OpenReadAsync(new Uri(sRequest, UriKind.Absolute));
 }
Пример #24
0
 private void getPage(string des)
 {
     string get = des;
     WebClient webClient = new WebClient();
     webClient.OpenReadAsync(new Uri("http://maps.googleapis.com/maps/api/geocode/xml?sensor=true&address=" + get));
     webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadComplete);
 }
Пример #25
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
        }
Пример #26
0
 protected void LoadRSS(string uri)
 {
     WebClient wc = new WebClient();
     wc.OpenReadCompleted += wc_OpenReadCompleted;
     Uri feedUri = new Uri(uri, UriKind.Absolute);
     wc.OpenReadAsync(feedUri);
 }
Пример #27
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            if (!HtmlPage.Document.QueryString.ContainsKey(ResourceManager.CultureParamName))
            {
                RootVisual = new MainPage();
                return;
            }

            string localeName = HtmlPage.Document.QueryString[ResourceManager.CultureParamName];
            WebClient client = new WebClient();

            client.OpenReadCompleted += delegate(object sender1, OpenReadCompletedEventArgs e1)
            {
                AssemblyPart part = new AssemblyPart();
                part.Load(e1.Result);

                ResourceManager.SetCulture(localeName);

                RootVisual = new MainPage();
            };

            string absoluteUri = HtmlPage.Document.DocumentUri.AbsoluteUri;
            string address = absoluteUri.Substring(0, absoluteUri.LastIndexOf("/"));

            client.OpenReadAsync(
                new Uri(
                    string.Format("{0}/ClientBin/{1}/Bonus.Praxis.SilverlightLocalization.resources.dll", address,
                                  localeName),
                    UriKind.Absolute));
        }
 private void btnCidade_click(object sender, RoutedEventArgs e)
 {
     WebClient client = new WebClient();
     client.OpenReadCompleted +=client_OpenReadCompleted;
     client.OpenReadAsync(new Uri("http://precosmarcenaria.herokuapp.com/cities.xml?q="+txtCidade.Text, UriKind.Absolute));
     txtBCidade.Text = "Procurando cidades...Por Favor, aguarde";
 }
Пример #29
0
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            string msg = "";
            if (NavigationContext.QueryString.TryGetValue("loc", out msg))
            {

                url = string.Concat("http://dev.virtualearth.net/REST/v1/Imagery/Map/Aerial/", msg, "/18?mapSize=300,300&pp=", msg, ";22&key=AuDYnNCuX6IO32SfDG38eldjOktHoKtvEyzOuOv1yMm7wAnmuu6h3K4ozwE5ghOx");

                Visibility darkBackgroundVisibility = (Visibility)Application.Current.Resources["PhoneDarkThemeVisibility"];

                if (darkBackgroundVisibility == Visibility.Visible)
                    //Theme is Dark
                    image1.Source = new BitmapImage(new Uri("/Image/icons/refresh_dark.png", UriKind.Absolute));
                else
                    image1.Source = new BitmapImage(new Uri("/Image/icons/refresh_white.png", UriKind.Absolute));

                var webClient = new WebClient();

                webClient.OpenReadAsync(new Uri("http://tinyurl.com/api-create.php?url=" + url));
                webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);

                //url = "http://dev.virtualearth.net/REST/v1/Imagery/Map/Road/41.9042835235596,12.54311466/15?mapSize=200,200&pp=41.9042835235596,12.54311466;22&key=AuDYnNCuX6IO32SfDG38eldjOktHoKtvEyzOuOv1yMm7wAnmuu6h3K4ozwE5ghOx";
                image1.Source = new BitmapImage(new Uri(url, UriKind.Absolute));

                //image1.Source =  new BitmapImage(new Uri(url, UriKind.Absolute));

            }
        }
Пример #30
0
 public static Boolean LogIn(string userName, string password)
 {
     WebClient webClient = new WebClient();
     webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(authUser_OpenReadCompletedEventArgs);
     webClient.OpenReadAsync(new Uri(""));
     return authentification;
 }
Пример #31
0
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {

            if (a != null)
            {
                textBox1.Text = string.Format("这个有意思 →_→【{0}】{1}(分享自 @果壳网)", a.title, a.wwwurl);
                if (!string.IsNullOrEmpty(a.pic))
                {
                    string large_pic_uri = a.pic.Replace("/img2.", "/img1.").Replace("thumbnail", "gkimage").Replace("_90", "");

                    var large_uri = new Uri(large_pic_uri, UriKind.Absolute);
                    var _imgsrc = new BitmapImage();
                    WebClient wc = new WebClient();
                    wc.Headers["Referer"] = "http://www.guokr.com";
                    wc.OpenReadCompleted += (s, ee) =>
                        {
                            try
                            {
                                _imgsrc.SetSource(ee.Result);
                            }
                            catch
                            {

                            }
                        };
                    wc.OpenReadAsync(large_uri);
                    _imgsrc.ImageFailed += (ss, ee) => _imgsrc.UriSource = new Uri(a.pic, UriKind.Absolute);
                    image_preview.Source = _imgsrc;
                }
            }

            sending_popup.Visibility = System.Windows.Visibility.Collapsed;
        }
Пример #32
0
 private void DownloadVideo()
 {
     WebClient webClient = new WebClient();
     webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
     webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
     webClient.OpenReadAsync(new Uri(App.videoURL));
 }
 public Task<Stream> DownloadFile(Uri url)
 {
     var tcs = new TaskCompletionSource<Stream>();
     var wc = new WebClient();
     wc.OpenReadCompleted += (s, e) =>
     {
         if (e.Error != null)
         {
             tcs.TrySetException(e.Error);
             return;
         }
         else if (e.Cancelled)
         {
             tcs.TrySetCanceled();
             return;
         }
         else tcs.TrySetResult(e.Result);
     };
     wc.OpenReadAsync(url);
     MessageBoxResult result = MessageBox.Show("Started downloading media. Do you like to stop the download ?", "Purpose Color", MessageBoxButton.OKCancel);
     if( result == MessageBoxResult.OK )
     {
         progress.HideProgressbar();
         wc.CancelAsync();
         return null;
     }
     return tcs.Task;
 }
Пример #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;
        }
Пример #35
0
        public FirebaseStreamParser(string route, string baseUrl)
        {
            toSend = new Queue <Dictionary <string, object> >();
            //  dataCache = new DataBranch();
            BaseUrl  = baseUrl;
            Added   += (k, e) => { };
            Changed += (k, e) => { };
            Deleted += (k, e) => { };

            Route         = route;
            receiveThread = new Thread(() =>
            {
                var client = new System.Net.WebClient();
                client.Headers.Add(System.Net.HttpRequestHeader.Accept, "text/event-stream");
                client.OpenReadCompleted += (s, e) =>
                {
                    using (StreamReader sr = new StreamReader(e.Result))
                    {
                        while (!sr.EndOfStream)
                        {
                            parse(sr.ReadLine());
                        }
                    }
                };
                client.OpenReadAsync(new Uri(baseUrl + route + ".json"));
            });
            receiveThread.IsBackground = true;
            receiveThread.Start();
            receiveThread.Name = ("FirebaseStreamParser -> " + route);
            sendThread         = new Thread(() =>
            {
                var client = new System.Net.WebClient();
                while (true)
                {
                    if (toSend.Count() != 0)
                    {
                        var uri = new Uri(baseUrl + route + ".json");
                        while (toSend.Count > 0)
                        {
                            var upd = toSend.Dequeue();
                            while (toSend.Count > 0 && tryJoin(upd, toSend.Peek()))
                            {
                                toSend.Dequeue();
                            }

                            //   var toUpdate = new DataBranch(upd.ToDictionary(entry => entry.Key, entry => (DataNode)new DataLeaf(entry.Value)));
                            //    dataCache.Merge(toUpdate);
                            client.UploadData(uri, "PATCH", Encoding.UTF8.GetBytes(serializeDictionary(upd)));
                        }
                    }

                    Thread.Sleep(10);
                }
            });
            sendThread.Name         = ("FirebaseStreamParser <- " + route);
            sendThread.IsBackground = true;
            sendThread.Start();
        }
Пример #36
0
        void dt_Tick(object sender, EventArgs e)
        {
            _dt.Stop();

            // go get the next xap file
            Uri addressUri = new Uri(_baseUri, "ClientBin/MultipleXap1.xap");

            System.Net.WebClient wcXap1 = new System.Net.WebClient();
            wcXap1.BaseAddress        = _baseUri;
            wcXap1.OpenReadCompleted += new OpenReadCompletedEventHandler(wcXap1_OpenReadCompleted);
            wcXap1.OpenReadAsync(addressUri);
        }
 void updateBingWallpaper()
 {
     try
     {
         WebClient client = new System.Net.WebClient();
         client.OpenReadCompleted += new System.Net.OpenReadCompletedEventHandler(client_OpenReadCompleted);
         client.OpenReadAsync(new Uri("http://appserver.m.bing.net/BackgroundImageService/TodayImageService.svc/GetTodayImage?dateOffset=-0&urlEncodeHeaders=true&osName=wince&osVersion=7.10&orientation=480x800&mkt=en-US&deviceName=donttreadonme&AppId=homebrew&UserId=rules&nocache=" + DateTime.Now.Millisecond.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.DayOfYear.ToString(), UriKind.Absolute));
     }
     catch (Exception ex)
     {
         msgbox("Exception in bing dler: " + ex.Message);
     }
 }
        /// <summary>
        /// Downloads the specified resource as a <see cref="Stream"/>.
        /// </summary>
        /// <param name="client">The object that downloads the resource.</param>
        /// <param name="address">A <see cref="Uri"/> containing the URI to download.</param>
        /// <returns>An observable containing the readable stream that reads data from the resource.</returns>
        public static IObservable <Stream> OpenReadObservable(
            this WebClient client,
            Uri address)
        {
            Contract.Requires(client != null);
            Contract.Requires(address != null);
            Contract.Ensures(Contract.Result <IObservable <Stream> >() != null);

            return(Observable2.FromEventBasedAsyncPattern <OpenReadCompletedEventHandler, OpenReadCompletedEventArgs>(
                       handler => handler.Invoke,
                       handler => client.OpenReadCompleted += handler,
                       handler => client.OpenReadCompleted -= handler,
                       token => client.OpenReadAsync(address, token),
                       client.CancelAsync)
                   .Select(e => e.EventArgs.Result));
        }
        /// <summary>
        /// Downloads the specified resource as a <see cref="Stream"/> and includes a channel for progress notifications.
        /// </summary>
        /// <param name="client">The object that downloads the resource.</param>
        /// <param name="address">A <see cref="Uri"/> containing the URI to download.</param>
        /// <returns>An observable that contains progress notifications in the left channel and the stream that
        /// reads data from the resource in the right channel.</returns>
        public static IObservable <Either <DownloadProgressChangedEventArgs, Stream> > OpenReadWithProgress(
            this WebClient client,
            Uri address)
        {
            Contract.Requires(client != null);
            Contract.Requires(address != null);
            Contract.Ensures(Contract.Result <IObservable <Either <DownloadProgressChangedEventArgs, Stream> > >() != null);

            return(Observable2.FromEventBasedAsyncPattern <OpenReadCompletedEventHandler, OpenReadCompletedEventArgs, DownloadProgressChangedEventHandler, DownloadProgressChangedEventArgs>(
                       handler => handler.Invoke,
                       handler => client.OpenReadCompleted += handler,
                       handler => client.OpenReadCompleted -= handler,
                       handler => handler.Invoke,
                       handler => client.DownloadProgressChanged += handler,
                       handler => client.DownloadProgressChanged -= handler,
                       token => client.OpenReadAsync(address, token),
                       client.CancelAsync)
                   .Select(
                       left => left.EventArgs,
                       right => right.EventArgs.Result));
        }
Пример #40
0
        /// <summary>Opens a readable stream for the data downloaded from a resource, asynchronously.</summary>
        /// <param name="webClient">The WebClient.</param>
        /// <param name="address">The URI for which the stream should be opened.</param>
        /// <returns>A Task that contains the opened stream.</returns>
        public static Task <Stream> OpenReadTask(this WebClient webClient, Uri address)
        {
            TaskCompletionSource <Stream> tcs     = new TaskCompletionSource <Stream>(address);
            OpenReadCompletedEventHandler handler = null;

            handler = delegate(object sender, OpenReadCompletedEventArgs e) {
                EAPCommon.HandleCompletion <Stream>(tcs, e, () => e.Result, delegate {
                    webClient.OpenReadCompleted -= handler;
                });
            };
            webClient.OpenReadCompleted += handler;
            try
            {
                webClient.OpenReadAsync(address, tcs);
            }
            catch (Exception exception)
            {
                webClient.OpenReadCompleted -= handler;
                tcs.TrySetException(exception);
            }
            return(tcs.Task);
        }