示例#1
2
 private void SendGETRequest(string url)
 {
     using (WebClient wc = new WebClient())
     {
         wc.DownloadStringAsync(new Uri(url));
     }
 }
示例#2
0
        private void go()
        {
            progressBar1.Visibility = System.Windows.Visibility.Visible;
            progressBar1.IsIndeterminate = true;
            WebClient WC = new WebClient();
             //           System.Text.Encoding.Convert(System.Text.Encoding.UTF8, System.Text.Encoding.GetEncoding("cp949"),query.Text);
            //            WC.Encoding=System.Text.Encoding.GetEncoding("cp949");
            var temp = EUCKR_Unicode_Library.EUCKR_Unicode_Converter.GetEucKRString(
                             query.Text
                         );
            var sb=new StringBuilder();
            foreach (byte i in temp)
            {
                sb.Append("%");
                sb.Append(i.ToString("X"));
            }
            var temp2 = System.Text.Encoding.UTF8.GetString(
                        temp, 0, temp.Length
                    );
            var temp3 = System.Net.HttpUtility.UrlEncode(
                    sb.ToString()
                );
            WC.DownloadStringAsync(new Uri("http://www.acornpub.co.kr/API/search.php?page=1&pageSize=25&keyword=" +
                sb.ToString()
               ));

            WC.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler(Completed);
        }
示例#3
0
    public void LoadJsonString(string url)
    {
        Debug.Log ("trying to load " + url);
        WebClient webClient = new WebClient ();

        webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownCompleted);
        webClient.DownloadStringAsync (new System.Uri(url));
    }
示例#4
0
 public void StartUp()
 {
     var clientByStartUp = new WebClient();
     string content = string.Format("Action=0&A=1&B=1&C={0}&C1={1}&D={2}&E={3}&F={4}&G={5}&H={6}&I={7}",
          C, C1, D, EpgUtils.ClientVersion, D, Y2, Y2, Y1);
     string uri = CreateUri(content);
     clientByStartUp.DownloadStringAsync(uri);
 }
示例#5
0
 public void Quit()
 {
     var runTime = DateTime.Now.Subtract(DataCommonUtils.AppStartTime).Seconds;
     var clientByQuit = new WebClient();
     string content = string.Format("Action=0&A=2&B=1&C={0}&C1={1}&D={2}&E={3}&F={4}&G={5}&H={6}&I=0&J={7}&K={8}", C, C1, D, EpgUtils.ClientVersion, D, Y2, Y2, runTime, Y1);
     string uri = CreateUri(content);
     clientByQuit.DownloadStringAsync(uri);
 }
 }/*}}}*/
 //03sub EAP2TPl Event-based Async Pattern
 static Task<string> DownloadStringAsTask(Uri address) {/*{{{*/
   TaskCompletionSource<string> tcs = 
     new TaskCompletionSource<string>();
   WebClient client = new WebClient();
   client.DownloadStringCompleted += (sender, args) => {
     if (args.Error != null) tcs.SetException(args.Error);
     else if (args.Cancelled) tcs.SetCanceled();
     else tcs.SetResult(args.Result);
   };
   client.DownloadStringAsync(address);
   return tcs.Task;
 }/*}}}*/
示例#7
0
文件: test.cs 项目: mono/gert
	static int Main ()
	{
		WebClient objClient = new WebClient ();
		objClient.DownloadStringCompleted += objClient_DownloadStringCompleted;
		objClient.DownloadStringAsync (new Uri ("http://www.google.com"));
		while (!_complete) {
		}
		if (_result == null)
			return 1;
		if (_result.IndexOf ("<html>") == -1)
			return 2;
		return 0;
	}
示例#8
0
        public void SearchAsync()
        {
            try
            {
                if (ValidaImportacao())
                {
                    WebClient client = new WebClient();
                    client.Encoding = System.Text.Encoding.UTF8;
                    client.DownloadStringCompleted += (sender, args) =>
                    {
                        if (!args.Cancelled && args.Error == null)
                        {
                            if (ValidaDados(args.Result))
                            {
                                // Investir
                                String                   sBody             = CortaTabelaInvestir(args.Result);
                                List <String>            lstData           = ProcessaTabela(sBody);
                                List <TesouroDiretoItem> lstDataProcessada = ProcessaDados(lstData, false);
                                SalvaDados(lstDataProcessada);

                                // Vender
                                sBody             = CortaTabelaVender(args.Result);
                                lstData           = ProcessaTabela(sBody);
                                lstDataProcessada = ProcessaDados(lstData, true);
                                SalvaDados(lstDataProcessada);
                            }
                        }
                    };
                    client.DownloadStringAsync(new Uri(url));
                }
            }
            catch (Exception e)
            {
                ErroHandler.Log("HunterTesouro", e, "SearchAsync", "");
                throw e;
            }
        }
示例#9
0
文件: Session.cs 项目: ticuth/JSIL
        private static void CheckForRunningWebServer()
        {
            var completedSignal = new ManualResetEventSlim(false);

            using (var wc = new WebClient()) {
                Exception fetchError  = null;
                string    fetchResult = null;

                wc.DownloadStringCompleted += (s, e) => {
                    try {
                        fetchResult = e.Result;
                    } catch (Exception exc) {
                        fetchError = exc;
                    }

                    completedSignal.Set();
                };

                wc.DownloadStringAsync(new Uri(LocalHost));

                completedSignal.Wait(2500);

                if (!completedSignal.IsSet)
                {
                    try {
                        wc.CancelAsync();
                    } catch (Exception exc) {
                        fetchError = fetchError ?? exc;
                    }
                }

                if (fetchResult == null)
                {
                    throw new Exception("Failed to connect to local web server at " + LocalHost, fetchError);
                }
            }
        }
示例#10
0
        internal static void LoadCalendarFeedIntoListBox(ObservableCollection <CalendarItem> Items, string url)
        {
            DispatcherHelper.CheckBeginInvokeOnUI(() => Items.Clear());
            WebClient client = new WebClient();

            client.DownloadStringCompleted += (sender, args) =>
            {
                if (args.Error == null)
                {
                    var xml = args.Result;
                    if (xml.Length > 0)
                    {
                        XDocument doc    = XDocument.Parse(xml);
                        var       events = from item in doc.Root.Element("channel").Elements("item")
                                           select new CalendarItem()
                        {
                            Details        = item.Element("description").Value,
                            Slug           = item.Element("title").Value,
                            EventDateStart = item.Element("pubDate").Value.ParseDateTime(),
                            Link           = item.Element("link").Value,
                        };
                        DispatcherHelper.CheckBeginInvokeOnUI(() =>
                        {
                            foreach (var @event in events)
                            {
                                Items.Add(@event);
                            }
                        });
                    }
                }
                else
                {
                    Messenger.Default.Send <ErrorMessage>(new ErrorMessage(args.Error));
                }
            };
            client.DownloadStringAsync(new Uri(url, UriKind.Absolute));
        }
 public void UpdatePACFromGFWList(Configuration config)
 {
     if (gfwlist_template == null)
     {
         lastConfig = config;
         WebClient http = new WebClient();
         http.Headers.Add("User-Agent",
                          String.IsNullOrEmpty(config.proxyUserAgent) ?
                          "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.3319.102 Safari/537.36"
             : config.proxyUserAgent);
         WebProxy proxy = new WebProxy(IPAddress.Loopback.ToString(), config.localPort);
         if (!string.IsNullOrEmpty(config.authPass))
         {
             proxy.Credentials = new NetworkCredential(config.authUser, config.authPass);
         }
         http.Proxy = proxy;
         http.DownloadStringCompleted += http_DownloadGFWTemplateCompleted;
         http.DownloadStringAsync(new Uri(GFWLIST_TEMPLATE_URL + "?rnd=" + Util.Utils.RandUInt32().ToString()));
     }
     else
     {
         WebClient http = new WebClient();
         http.Headers.Add("User-Agent",
                          String.IsNullOrEmpty(config.proxyUserAgent) ?
                          "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.3319.102 Safari/537.36"
             : config.proxyUserAgent);
         WebProxy proxy = new WebProxy(IPAddress.Loopback.ToString(), config.localPort);
         if (!string.IsNullOrEmpty(config.authPass))
         {
             proxy.Credentials = new NetworkCredential(config.authUser, config.authPass);
         }
         http.Proxy                    = proxy;
         http.BaseAddress              = GFWLIST_URL;
         http.DownloadStringCompleted += http_DownloadStringCompleted;
         http.DownloadStringAsync(new Uri(GFWLIST_URL + "?rnd=" + Util.Utils.RandUInt32().ToString()));
     }
 }
        public void Request_Purchase_Package_Service(int type)
        {
            string cmsURL = SystemParameter.REQUEST_PURCHASE_PACKAGE_SERVICE;

            cmsURL = cmsURL.Replace("%t", type.ToString());
            cmsURL = cmsURL + "&time=" + DateTime.Now;
            if (type == 1)
            {
                this.packageName = "Basic 1";
            }
            if (type == 2)
            {
                this.packageName = "Basic 2";
            }
            if (type == 3)
            {
                this.packageName = "Basic 3";
            }

            WebClient client = new WebClient();

            if ((App.Current as App).cookie != null && !(App.Current as App).cookie.Equals(""))
            {
                client.Headers["Cookie"] = (App.Current as App).cookie;
            }
            else
            {
                string old_cookie = getCookieFromIsolatedStorage();
                if (old_cookie != null && !old_cookie.Equals("") && old_cookie != "\r\n")
                {
                    client.Headers["Cookie"] = old_cookie;
                }
            }

            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_purchase_package_service_DownloadStringCompleted);
            client.DownloadStringAsync(new Uri(cmsURL));
        }
示例#13
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (radioButton1.Checked == false)
            {
                MessageBox.Show("订单状态未修改");
            }
            else
            {
                Uri uri = new Uri("http://localhost5001/api/TakeOut/UpdateOrder?TakeOutOrderID= " + takeoutorderid);

                using (WebClient c = new WebClient())
                {
                    //c.Headers["Type"]:获取数据的方式
                    c.Headers["Type"] = "Get";
                    //c.Headers["Accept"]:获取数据的格式
                    c.Headers["Accept"] = "application/json";
                    //c.Encoding:数据的编码格式。
                    c.Encoding = Encoding.UTF8;
                    //DownloadDataCompleted:在多线程情况下,能进行webApi数据传输。
                    c.DownloadStringCompleted += (senderobj, es) =>
                    {
                        //es.Result:如果获取的webapi之中的数据不为空,则绑定gv
                        if (es.Result != null)
                        {
                            if (es.Result == "\"OK\"")
                            {
                                MessageBox.Show("修改成功");
                                this.Close();
                                this.DialogResult = DialogResult.OK;
                            }
                        }
                    };
                    //把当前webApi地址释放掉。
                    c.DownloadStringAsync(uri);
                }
            }
        }
示例#14
0
        public string DownloadString(string url)
        {
            logger.Log("[SMEEDEE REQUEST]", url);
            Uri uri;

            try
            {
                url += (url.Contains("?") ? "&" : "?") + "nocache=" + new Random().Next();
                uri  = new Uri(url);
            } catch (FormatException)
            {
                return("");
            }
            var manualReset = new ManualResetEvent(false);
            var client      = new WebClient();

            var result = "";

            client.DownloadStringCompleted += (o, e) =>
            {
                if (e.Error == null)
                {
                    result = e.Result;
                }
                else
                {
                    logger.Log("[SMEEDEE HttpError]", "" + e.Error);
                }
                manualReset.Set();
            };
            client.DownloadStringAsync(uri);

            manualReset.WaitOne(TIMEOUT);

            logger.Log("[SMEEDEE RESULT]", result);
            return(result);
        }
示例#15
0
 private static void DownloadStringAsync2Internal(this WebClient request, Uri address, DownloadStringCompletedEventHandler2 callback, object userToken, int attempt)
 {
     if (attempt == 1)
     {
         request.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e)
         {
             if (e.Error != null && attempt == 1)
             {
                 try
                 {
                     WebException    ex = (WebException)e.Error;
                     HttpWebResponse httpWebResponse = (HttpWebResponse)ex.Response;
                     if (httpWebResponse.StatusCode == HttpStatusCode.ProxyAuthenticationRequired)
                     {
                         request.Proxy = new WebProxy();
                         request.UseDefaultCredentials = true;
                         request.Proxy.Credentials     = CredentialCache.DefaultCredentials;
                         request.DownloadStringAsync2Internal(address, callback, userToken, ++attempt);
                         return;
                     }
                 }
                 catch
                 {
                 }
             }
             CallState callState = e.UserState as CallState;
             DownloadStringCompletedEventHandler2 downloadStringCompletedEventHandler = callState.Callback as DownloadStringCompletedEventHandler2;
             DownloadStringCompletedEventArgs2    e2 = new DownloadStringCompletedEventArgs2(e.Result, e.Error, e.Cancelled, callState.Data);
             downloadStringCompletedEventHandler(callState.Data, e2);
         };
     }
     request.DownloadStringAsync(address, new CallState
     {
         Callback = callback,
         Data     = userToken
     });
 }
示例#16
0
        /// <summary>Searches for the specified query in the specified area.</summary>
        /// <param name="query">The information to search for.</param>
        /// <param name="area">The area to localize results.</param>
        /// <returns>True if search has started, false otherwise.</returns>
        /// <remarks>
        /// The query is first parsed to see if it is a valid coordinate, if not then then a search
        /// is carried out using nominatim.openstreetmap.org. A return valid of false, therefore,
        /// doesn't indicate the method has failed, just that there was no need to perform an online search.
        /// </remarks>
        public override bool Search(string query, Rect area)
        {
            query = (query ?? string.Empty).Trim();
            if (query.Length == 0)
            {
                return(false);
            }
            if (this.TryParseLatitudeLongitude(query))
            {
                return(false);
            }

            string bounds = string.Format(
                CultureInfo.InvariantCulture,
                "{0:f4},{1:f4},{2:f4},{3:f4}",
                area.Left,
                area.Bottom, // Area is upside down
                area.Right,
                area.Top);

            WebClient client = new WebClient();

            client.QueryString.Add("q", Uri.EscapeDataString(query));
            client.QueryString.Add("viewbox", Uri.EscapeDataString(bounds));
            client.QueryString.Add("format", "xml");
            try
            {
                client.DownloadStringCompleted += this.OnDownloadStringCompleted;
                client.DownloadStringAsync(new Uri(SearchPath));
            }
            catch (WebException ex) // An error occurred while downloading the resource
            {
                this.OnSearchError(ex.Message);
                return(false);
            }
            return(true);
        }
        public override void Initialize()
        {
            // First - retrieve metadata for the service (if geometry is not known)
            if (RetrieveMetaDataOnStartup && Uri.IsWellFormedUriString(Url, System.UriKind.Absolute))
            {
                string metaDataUrl = Url;
                if (!metaDataUrl.Contains("f=json"))
                {
                    if (!metaDataUrl.Contains("?"))
                    {
                        metaDataUrl += "?f=json";
                    }
                    else
                    {
                        metaDataUrl += "&f=json";
                    }
                }

                WebClient wc = new WebClient();
                wc.DownloadStringCompleted += (o, e) =>
                {
                    if (e.Error != null || string.IsNullOrEmpty(e.Result))
                    {
                        System.Diagnostics.Debug.WriteLine(e.Error.Message);
                        System.Diagnostics.Debug.WriteLine(e.Error.StackTrace);
                        base.Initialize();
                        return;
                    }
                    parseLayerDetailsFromResponse(e.Result);
                };
                wc.DownloadStringAsync(new Uri(metaDataUrl, UriKind.Absolute));
            }
            else
            {
                base.Initialize();
            }
        }
示例#18
0
        public void CheckForUpdatesAsync()
        {
            IniData data = SettingsController.GetCurrentSettings();

            WebClient client = new WebClient();

            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;
            client.Headers.Add("user-agent", "request");
            client.DownloadStringAsync(new Uri("https://api.github.com/repos/nik9play/tinyBrightness/releases/latest"));
            client.DownloadStringCompleted += (sender, e) =>
            {
                try
                {
                    JObject json_res            = JObject.Parse(e.Result);
                    Version version             = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
                    int     CurrentVersionMinor = version.Minor;
                    NewVersionMinor  = int.Parse(json_res["tag_name"].ToString().Split('.')[1]);
                    NewVersionString = json_res["tag_name"].ToString();

                    //1 is exe and 0 is zip
                    DownloadUrl  = json_res["assets"][1]["browser_download_url"].ToString();
                    Description  = json_res["name"].ToString();
                    ChangeLogUrl = json_res["html_url"].ToString();

                    if ((NewVersionMinor > CurrentVersionMinor) && (data["Updates"]["SkipVersion"] != json_res["tag_name"].ToString()))
                    {
                        OnCheckingCompleted(true);
                    }
                    else
                    {
                        OnCheckingCompleted(false);
                    }
                }
                catch { OnCheckingCompleted(false); }
            };
        }
示例#19
0
        /// <summary>
        /// Sign out from the application.
        /// </summary>
        public static async void SignOut()
        {
            var    client    = ServiceLocator.Current.GetInstance <IMyCompanyClient>();
            string logoutUrl = await client.SecurityService.GetLogoutUrl();

            logoutUrl = WebUtility.UrlDecode(logoutUrl);
            IsolatedStorageSettings.ApplicationSettings.Remove("token");
            EmployeeInformation = null;

            while (App.RootFrame.BackStack.Any())
            {
                App.RootFrame.RemoveBackEntry();
            }

            if (!string.IsNullOrEmpty(logoutUrl))
            {
                WebClient c = new WebClient();
                c.DownloadStringAsync(new Uri(logoutUrl));
                c.DownloadStringCompleted += (s, e) =>
                {
                    App.RootFrame.Navigate(new Uri("/Views/AuthenticationPage.xaml", UriKind.Relative));
                };
            }
        }
示例#20
0
        private void BtnInserePosseder_Click(object sender, EventArgs e)
        {
            if (txtCoef.Text != "" && txtDiplome.Text != "")
            {
                var      coefConvert = Convert.ToDouble(txtCoef.Text);
                Posseder checkP      = new Posseder()
                {
                    codeSPE = speSelectione.codeSPE, idPRT = praSelectione.idPRA, coefPOS = coefConvert, diplomePOS = txtDiplome.Text, libelleSPE = speSelectione.libelleSPE
                };


                var t     = allPosseders.Find(x => x.idPRT == praSelectione.idPRA);
                var check = "";
                if (t != null)
                {
                    check = allPosseders.Find(x => x.idPRT == praSelectione.idPRA).codeSPE;
                }

                if (check == speSelectione.codeSPE)
                {
                    Toast.MakeText(this, "Praticien " + praSelectione.prenomPRA + " " + praSelectione.nomPRA + " a deja cette specialite", ToastLength.Short).Show();
                }
                else
                {
                    Uri url = new Uri("http://" + GetString(Resource.String.ip) + "insertPosseder.php?codeSPE=" + speSelectione.codeSPE + "&codePRA=" + praSelectione.idPRA + "&coef=" + txtCoef.Text + "&diplome=" + txtDiplome.Text);
                    ws.DownloadStringAsync(url);
                    Intent intent = new Intent(this, typeof(SpecialiteDePraticien));
                    StartActivity(intent);
                    ws.DownloadDataCompleted += Ws_DownloadDataCompleted;
                }
            }
            else
            {
                Toast.MakeText(this, "Veuillez saisir les données", ToastLength.Short).Show();
            }
        }
示例#21
0
        private static void Cancelling()
        {
            var webClient = new WebClient();

            webClient.DownloadStringCompleted += (sender, args) =>
            {
                webClient.Dispose();
                if (args.Cancelled)
                {
                    // handle cancellation
                }
                else if (args.Error != null)
                {
                    // handle error
                }
                else
                {
                    var contents = args.Result;
                    // process the result
                }
            };

            webClient.DownloadStringAsync(url);
        }
示例#22
0
        /// <summary>
        /// Download the user's webUI version file, compare the version with the latest one
        /// </summary>
        private void CheckForUpdate()
        {
            try
            {
                var lpath = Path.Combine(Common.AppdataFolder, @"version.ini");
                _controller.Client.Download("webint/version.ini", lpath);

                var ini            = new IniFile(lpath);
                var currentversion = ini.ReadValue("Version", "latest");

                var wc = new WebClient();
                wc.DownloadStringCompleted += (s, e) =>
                {
                    var vinfo = (WebInterfaceVersionInfo)JsonConvert.DeserializeObject(e.Result, typeof(WebInterfaceVersionInfo));

                    if (!vinfo.Uptodate)
                    {
                        UpdateFound.SafeInvoke(null, EventArgs.Empty);
                    }
                    else
                    {
                        Log.Write(l.Client, "Web Interface is up to date");
                    }

                    File.Delete(lpath);
                };
                var link = string.Format("http://ftpbox.org/webui.php?version={0}", currentversion);

                wc.DownloadStringAsync(new Uri(link));
            }
            catch (Exception ex)
            {
                Log.Write(l.Warning, "Error with version checking");
                Common.LogError(ex);
            }
        }
示例#23
0
 private void AccessingPageWithoutCheck(Uri address)
 {
     new Task(() =>
     {
         using (WebClient webClient = new WebClient())
         {
             webClient.Encoding = System.Text.Encoding.UTF8;
             webClient.DownloadStringCompleted +=
                 (sender, e) =>
             {
                 if (e.Error == null)
                 {
                     OldUrls.Add(address.ToString());
                     List <string> urls = LinkExtractor.ExtractUrlSameHost(e.Result, address.ToString());
                     foreach (var url in urls.ToList())
                     {
                         string strUrl = url;
                         if (!strUrl.EndsWith("/"))
                         {
                             if (!Path.HasExtension(new Uri(strUrl).AbsolutePath))
                             {
                                 strUrl = url + "/";
                             }
                         }
                         if (!NewUrls.Contains(strUrl) && (!OldUrls.Contains(strUrl)))
                         {
                             NewUrls.Add(strUrl);
                         }
                         Console.WriteLine(strUrl);
                     }
                 }
             };
             webClient.DownloadStringAsync(address);
         }
     }).Start();
 }
示例#24
0
        private static Task <string> GetHtmlStringAsync(string url)
        {
            var tcs = new TaskCompletionSource <string>();

            var client = new WebClient()
            {
                Encoding = DBCSEncoding.GetDBCSEncoding("gb2312")
            };

            client.DownloadStringCompleted += (s, e) =>
            {
                if (e.Error == null)
                {
                    tcs.SetResult(e.Result);
                }
                else
                {
                    tcs.SetException(e.Error);
                }
            };

            client.DownloadStringAsync(new Uri(url));
            return(tcs.Task);
        }
示例#25
0
        private void GetProductsByIDs(string[] ids, Action <IEnumerable <Product> > productsCallback)
        {
            WebClient webClient = new WebClient();

            webClient.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e) {
                List <Product> products = new List <Product>();

                if ((e.Cancelled == false) && (e.Error == null))
                {
                    string xml = e.Result;

                    if (String.IsNullOrEmpty(xml) == false)
                    {
                        ParseProducts(xml, products);
                    }
                }

                productsCallback(products);
            };

            Uri requestUri = new Uri(String.Format(LookupUriFormat, SubscriptionID, String.Join(",", ids)));

            webClient.DownloadStringAsync(requestUri);
        }
示例#26
0
        public void CheckUpdates()
        {
            if (IsUpdating)
            {
                return;
            }

            IsUpdating = true;
            m_playCommand.RaiseCanExecuteChanged();

            SetState("Téléchargement des informations ...");

            m_client = new WebClient();
            m_client.DownloadProgressChanged += OnDownloadProgressChanged;
            m_client.DownloadStringCompleted += OnPatchDownloaded;
            try
            {
                m_client.DownloadStringAsync(new Uri(Constants.UpdateSiteURL + Constants.RemotePatchFile), Constants.RemotePatchFile);
            }
            catch (SocketException)
            {
                SetState("Le serveur est indisponible");
            }
        }
示例#27
0
        private void GetProductsByKeyword(string keyword, Action <IEnumerable <Product>, bool> productsCallback)
        {
            WebClient webClient = new WebClient();

            webClient.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e) {
                List <Product> products = new List <Product>();

                if ((e.Cancelled == false) && (e.Error == null))
                {
                    string xml = e.Result;

                    if (String.IsNullOrEmpty(xml) == false)
                    {
                        ParseProducts(xml, products);
                    }
                }

                productsCallback(products, true);
            };

            Uri searchUri = new Uri(String.Format(SearchUriFormat, SubscriptionID, keyword));

            webClient.DownloadStringAsync(searchUri);
        }
示例#28
0
        public void GetPopularProducts(Action <IEnumerable <Product>, bool> productsCallback)
        {
            WebClient webClient = new WebClient();

            webClient.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e) {
                if ((e.Cancelled == false) && (e.Error == null))
                {
                    int feedIndex = (int)e.UserState;
                    feedIndex++;

                    string xml = e.Result;
                    try {
                        List <string> ids = new List <string>();

                        ParseProductIDs(xml, ids);
                        GetProductsByIDs(ids.ToArray(), (productResults) => {
                            bool completed = feedIndex == PopularFeedUrls.Length;

                            if (productResults != null)
                            {
                                productsCallback(productResults, completed);
                            }

                            if (completed == false)
                            {
                                ((WebClient)sender).DownloadStringAsync(new Uri(PopularFeedUrls[feedIndex]), feedIndex);
                            }
                        });
                    }
                    catch {
                    }
                }
            };

            webClient.DownloadStringAsync(new Uri(PopularFeedUrls[0]), 0);
        }
示例#29
0
 public void ExecuteJob(string taskParam)
 {
     if (!string.IsNullOrEmpty(taskParam))
     {
         WebClient wc = new WebClient();
         wc.Encoding = System.Text.Encoding.UTF8;
         wc.UseDefaultCredentials = true;
         foreach (string url in taskParam.Split(','))
         {
             try
             {
                 wc          = new WebClient();
                 wc.Encoding = System.Text.Encoding.UTF8;
                 wc.UseDefaultCredentials    = true;
                 wc.DownloadStringCompleted += wc_DownloadStringCompleted;
                 wc.DownloadStringAsync(new Uri(url));
             }
             catch (Exception ex)
             {
                 LogHelper.Debug(string.Format("异常信息>{0}\r\n", ex));
             }
         }
     }
 }
        /// <summary>
        /// Get Windows phone network ip address
        /// you can check this out : Getting the local IP address for a socket/network interface
        /// [ http://stackoverflow.com/questions/6968867/getting-the-local-ip-address-for-a-socket-network-interface]
        /// or visit the http://www.whatismyip.org/ have same result
        /// </summary>
        public void GetNetworkIpAddress()
        {
            string    IPPATTERN = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
            WebClient client    = new WebClient();

            client.DownloadStringCompleted += (s, e) =>
            {
                if (e.Error == null)
                {
                    string result            = e.Result;
                    Regex  ipRegex           = new Regex(IPPATTERN);
                    var    matchesCollection = ipRegex.Matches(result);
                    if (matchesCollection.Count != 0)
                    {
                        string IP = matchesCollection[0].Value;
                        if (GetNetWorkIpComplated != null)
                        {
                            GetNetWorkIpComplated(IP, null);
                        }
                    }
                }
            };
            client.DownloadStringAsync(new Uri("http://whatismyipaddress.com/", UriKind.Absolute));
        }
        // get a media stream uri from accountId, appName and a fileName if the request if for a non xap resource.
        public void getMediaStreamUri(string accountId, string appName, string fileName)
        {
            TimeSpan t            = (DateTime.UtcNow - new DateTime(1970, 1, 1));
            double   timestamp    = t.TotalMilliseconds;
            string   milliseconds = timestamp.ToString().Split(new char[] { '.' })[0];

            Uri targetUri;

            // check if we are requesting a media file or a xap application
            // because for some reason the format is different...
            if (fileName.Length != 0)
            {
                targetUri = new Uri(SLSMediaServiceRoot + string.Format("invoke/local/starth.js?id=bl2&u={0}&p0=/{1}/{2}/{3}", milliseconds, accountId, appName, fileName));
            }
            else
            {
                targetUri = new Uri(SLSMediaServiceRoot + string.Format("invoke/{1}/{2}/starth.js?id=bl2&u={0}", milliseconds, accountId, appName));
            }

            WebClient webClient = new WebClient();

            webClient.DownloadStringAsync(targetUri);
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
        }
示例#32
0
        /// <summary>
        /// Http同步Get异步请求
        /// </summary>
        /// <param name="url">Url地址</param>
        /// <param name="callBackDownStringCompleted">回调事件</param>
        /// <param name="encode">编码(默认UTF8)</param>
        public void HttpGetAsync(string url,
                                 DownloadStringCompletedEventHandler callBackDownStringCompleted = null, Encoding encode = null)
        {
            try
            {
                var webClient = new WebClient {
                    Encoding = Encoding.UTF8
                };

                if (encode != null)
                {
                    webClient.Encoding = encode;
                }

                if (callBackDownStringCompleted != null)
                {
                    webClient.DownloadStringCompleted += callBackDownStringCompleted;
                }

                webClient.DownloadStringAsync(new Uri(url));
            }
            catch (Exception e)
            { }
        }
示例#33
0
        private static void DownloadVersionStringCompleted(object sender, DownloadStringCompletedEventArgs args)
        {
            try
            {
                // Convert version string
                DataVersion = JsonConvert.DeserializeObject <string[]>(args.Result)[0];
            }
            catch (Exception e)
            {
                Logger.Exception("[SkinChanger] Failed to convert version string to array!\nVersion string: {0}", e, args.Result);
            }

            // Validate version
            if (string.IsNullOrWhiteSpace(DataVersion))
            {
                return;
            }

            Task.Run(async() =>
            {
                // Download data for each champion
                using (var webClient = new WebClient())
                {
                    webClient.DownloadStringCompleted += ChampionDataDownloaded;

                    foreach (var hero in EntityManager.Heroes.AllHeroes.Where(o => HeroMenus.ContainsKey(o.NetworkId)).Select(o => o.Hero).Unique())
                    {
                        while (webClient.IsBusy)
                        {
                            await Task.Delay(50);
                        }
                        webClient.DownloadStringAsync(new Uri(string.Format(RequestFormat, DataVersion, hero), UriKind.Absolute));
                    }
                }
            });
        }
示例#34
0
        /// <summary>
        /// Checks the server for any updates.
        /// </summary>
        public void CheckForUpdate()
        {
            //url to fetch from.
            string webpageURL = "URL TO WATCH AND PARSE";
            //Make a new webclient and uri for url.
            WebClient client = new WebClient();
            Uri       uri    = new Uri(webpageURL);

            //Handle completion callback.
            client.DownloadStringCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {
                    HandleUpdateCheckResponse(true, e.Result);
                }
                else
                {
                    HandleUpdateCheckResponse(false, string.Empty);
                }
            };

            //Begin requesting url.
            client.DownloadStringAsync(uri);
        }
 public override void FireRequest(Action <object, AsyncCompletedEventArgs> callback = null)
 {
     emitted = DateTime.Now;
     try {
         using (client = new WebClient()) {
             if (callback != null)
             {
                 client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(callback);
             }
             if (!string.IsNullOrEmpty(bearer))
             {
                 client.Headers.Add("Authorization", "Bearer " + bearer);
             }
             client.Headers.Add("Keep-Alive", "timeout=15, max=100");
             //if ( compression == true )
             //	client.Headers.Add ("Accept-Encoding", "gzip, deflate");
             state = SceneLoadingStatus.ePending;
             client.DownloadStringAsync(uri, this);
         }
     } catch (Exception ex) {
         Debug.Log(ForgeLoader.GetCurrentMethod() + " " + ex.Message);
         state = SceneLoadingStatus.eError;
     }
 }
示例#36
0
        void downloadApplicationSettingsFile(bool force)
        {
            if (m_IsDownloadingApplicationSettingsFile)
            {
                return;
            }

            if (!force)
            {
                if (!string.IsNullOrWhiteSpace(applicationSettingsFileContents))
                {
                    initializeDataContext(applicationSettingsFileContents);
                    return;
                }
            }

            if (!string.IsNullOrWhiteSpace(ApplicationSettingsFilePath))
            {
                WebClient applicationSettingsFileRequestClient = new WebClient();
                applicationSettingsFileRequestClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(ApplicationSettingsFileDownloadComplete);
                m_IsDownloadingApplicationSettingsFile = true;
                applicationSettingsFileRequestClient.DownloadStringAsync(new Uri(BaseUri, ApplicationSettingsFilePath));
            }
        }
示例#37
0
        private void button1_Click(object sender, EventArgs e)      //Start button
        {
            using (client = new WebClient())
            {
                client.DownloadStringCompleted += (s, ev) =>        //Download complete
                {
                    oldList = ev.Result.Split('\r').ToList();       //spit webpage up into paragraphs using the carriage return
                    Console.WriteLine("Start Timer");
                    timer1.Tick    += Timer1_Tick;                  //Start timer, every 10 seconds re-download webpage
                    timer1.Interval = 10 * 1000;
                    timer1.Start();
                    client.Dispose();

                    // Creates an HttpWebRequest for the specified URL.
                    myHttpWebRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
                    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
                    pageChange          = myHttpWebResponse.LastModified;
                    labelStartTime.Text = "Baseline: " + pageChange.ToString();
                    myHttpWebResponse.Close();
                };

                client.DownloadStringAsync(new Uri(url));                                  //Download webpage as one string
            }
        }
 //async topPage url parsing:
 private void BeginParseTopicPageURL(string url)
 {
     WebClient wc = new WebClient();
     wc.DownloadStringCompleted +=new DownloadStringCompletedEventHandler(wc_topic_DownloadStringCompleted);
     wc.DownloadStringAsync(new Uri(url));
 }
示例#39
0
        public void Play(DACPlayInfo playInfo, int playType)
        {
            var clientByPlayEnd = new WebClient();

            var builder = new StringBuilder(100);
            builder.AppendFormat("Action=0&A={0}&B=1&C={1}&C1={2}&VVID={3}&D={4}", playType, C, C1, playInfo.vvid, D);

            if (PersonalFactory.Instance.Logined)
            {
                var d1 = PersonalFactory.Instance.DataInfos[0].UserStateInfo.VIP == 0 ? "1" : "2";
                builder.AppendFormat("&D1={0}&D2={1}", d1, PersonalFactory.Instance.DataInfos[0].UserStateInfo.UserName);
            }
            else
            {
                builder.Append("&D1=0");
            }
            builder.AppendFormat("&D3={0}", WAYGetFactory.WayGetInfo.UserType);
            builder.AppendFormat("&E={0}", EpgUtils.ClientVersion);
            builder.AppendFormat("&F={0}&F1=1", playInfo.type);
            builder.AppendFormat("&G={0}", playInfo.vid);
            builder.AppendFormat("&H={0}", playInfo.title);
            builder.AppendFormat("&I={0}", playInfo.playTime);
            builder.AppendFormat("&J={0}", playInfo.mp4Name);
            builder.AppendFormat("&FT={0}", playInfo.ft);
            builder.AppendFormat("&FN={0}", playInfo.fn);
            builder.AppendFormat("&FM={0}", playInfo.allTime);
            builder.AppendFormat("&K={0}", playInfo.programSource);
            builder.AppendFormat("&L={0}", playInfo.prepareTime);
            builder.AppendFormat("&M={0}", playInfo.bufferTime);
            builder.AppendFormat("&N={0}", playInfo.allBufferCount);
            builder.AppendFormat("&O={0}", playInfo.dragCount);
            builder.AppendFormat("&P={0}", playInfo.dragBufferTime);
            builder.AppendFormat("&Q={0}", playInfo.playBufferCount);
            builder.AppendFormat("&R={0}", playInfo.connType);
            builder.AppendFormat("&S={0}", playInfo.isPlaySucceeded);
            builder.AppendFormat("&T={0}", 1);
            builder.AppendFormat("&U={0}", string.Empty);
            builder.AppendFormat("&V={0}", playInfo.averageDownSpeed);
            builder.AppendFormat("&W={0}", playInfo.stopReason);
            builder.AppendFormat("&Y1={0}", Y1);
            builder.AppendFormat("&Y2={0}", Y2);
            builder.AppendFormat("&Y3={0}", Y2);

            var uri = CreateUri(builder.ToString());
            clientByPlayEnd.DownloadStringAsync(uri);
        }
示例#40
0
        public static void DownloadString_InvalidArguments_ThrowExceptions()
        {
            var wc = new WebClient();

            Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadString((string)null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadString((Uri)null); });

            Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadStringAsync((Uri)null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadStringAsync((Uri)null, null); });

            Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadStringTaskAsync((string)null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadStringTaskAsync((Uri)null); });
        }
示例#41
0
 public static async Task ConcurrentOperations_Throw()
 {
     await LoopbackServer.CreateServerAsync((server, url) =>
     {
         var wc = new WebClient();
         Task ignored = wc.DownloadDataTaskAsync(url); // won't complete
         Assert.Throws<NotSupportedException>(() => { wc.DownloadData(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadDataAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadDataTaskAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadString(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadStringAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadStringTaskAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadFile(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadFileAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadFileTaskAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadData(url, new byte[42]); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadDataAsync(url, new byte[42]); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadDataTaskAsync(url, new byte[42]); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadString(url, "42"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadStringAsync(url, "42"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadStringTaskAsync(url, "42"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadFile(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadFileAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadFileTaskAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadValues(url, new NameValueCollection()); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadValuesAsync(url, new NameValueCollection()); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadValuesTaskAsync(url, new NameValueCollection()); });
         return Task.CompletedTask;
     });
 }
 // asych url string downloading functions
 private void BeginParseImageURL(string url)
 {
     WebClient wc = new WebClient();
     wc.Encoding = System.Text.Encoding.GetEncoding(936);
     wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
     wc.DownloadStringAsync(new Uri(url));
 }
示例#43
0
        public void Reload()
        {
            if (IsLoading)
                return;

            var wc = new WebClient();

            wc.DownloadStringCompleted += (sender, args) =>
            {
                _wc = null;

                if (args.Cancelled || args.Error != null)
                    return;

                var contentType = wc.ResponseHeaders[HttpResponseHeader.ContentType]
                                        .MaskNull().Split(new[] { ';' }, 2)[0];

                var jsonContentTypes = new[] {
                    "application/json", 
                    "application/x-javascript", 
                    "text/javascript",
                };

                if (!jsonContentTypes.Any(s => s.Equals(contentType, StringComparison.OrdinalIgnoreCase)))
                    return;

                using (var sc = new ScriptControl { Language = "JavaScript" })
                {
                    var data = sc.Eval("(" + args.Result + ")"); // TODO: JSON sanitization

                    ClosedStatuses = new ReadOnlyCollection<string>(
                        new OleDispatchDriver(data)
                           .Get<IEnumerable>("closed")
                           .Cast<object>()
                           .Select(o => new OleDispatchDriver(o).Get<string>("name"))
                           .ToArray());
                }

                IsLoaded = true;
                OnLoaded();
            };

            wc.DownloadStringAsync(IssueOptionsFeedUrl());
            _wc = wc;
        }
示例#44
0
        public Action DownloadIssues(string project, int start, bool includeClosedIssues,
            Func<IEnumerable<Issue>, bool> onData,
            Action<DownloadProgressChangedEventArgs> onProgress,
            Action<bool, Exception> onCompleted)
        {
            Debug.Assert(project != null);
            Debug.Assert(onData != null);

            var client = new WebClient();

            Action<int> pager = next => client.DownloadStringAsync(
                new GoogleCodeProject(project).IssuesCsvUrl(next, includeClosedIssues));

            client.DownloadStringCompleted += (sender, args) =>
            {
                if (args.Cancelled || args.Error != null)
                {
                    if (onCompleted != null)
                        onCompleted(args.Cancelled, args.Error);

                    return;
                }

                var issues = IssueTableParser.Parse(new StringReader(args.Result)).ToArray();
                var more = onData(issues);

                if (more)
                {
                    start += issues.Length;
                    pager(start);
                }
                else
                {
                    if (onCompleted != null)
                        onCompleted(false, null);
                }
            };

            if (onProgress != null)
                client.DownloadProgressChanged += (sender, args) => onProgress(args);

            pager(start);

            return client.CancelAsync;
        }
示例#45
0
    private void _request(string[] request, AsyncResponse callback = null, string query = "")
    {
        WebClient client = new WebClient ();
        string url = origin + String.Join("/", request) + "?" + query;
        debug( url );
        client.Headers.Add("V","1.0");
        client.Headers.Add("User-Agent","Unity3D");
        client.DownloadStringCompleted += (s,e) => {
            if( callback != null ) {
                Hashtable response = new Hashtable();
                if(e.Cancelled != false || e.Error != null) {
                    response.Add("error", true);
                }
                else {
                    response.Add("message", (ArrayList)JSON.JsonDecode((string)e.Result));
                }
                callback( response );
            }
            client.Dispose();
        };

        client.DownloadStringAsync(new Uri( url ));
    }
示例#46
0
        // it's actually impossible to really show this old-style in a Windows Store app
        // the non-async APIs just don't exist :-)
        public void DownloadHomepage()
        {
            var webClient = new WebClient(); // not in Windows Store APIs

            webClient.DownloadStringCompleted += (sender, e) =>
            {
                if (e.Cancelled || e.Error != null)
                {
                    // do something with error
                }
                string contents = e.Result;

                int length = contents.Length;
                Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    ResultTextView.Text += "Downloaded the html and found out the length.\n\n";
                });
                webClient.DownloadDataCompleted += (sender1, e1) =>
                {
                    if (e1.Cancelled || e1.Error != null)
                    {
                        // do something with error
                    }
                    SaveBytesToFile(e1.Result, "team.jpg");

                    Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        ResultTextView.Text += "Downloaded the image.\n";

                        var img = ApplicationData.Current.LocalFolder.GetFileAsync("team.jpg");
                        var i = new BitmapImage(new Uri(img.Path, UriKind.Absolute));
                        DownloadedImageView.Source = i;
                    });

                    if (downloaded != null)
                        downloaded(length);
                };
                webClient.DownloadDataAsync(new Uri("http://xamarin.com/images/about/team.jpg"));
            };

            webClient.DownloadStringAsync(new Uri("http://xamarin.com/"));
        }
    private void RefreshData()
    {
        richTextBox1.Text += dot + "Checking for updates...\n";

        WebClient client = new WebClient();
        client.DownloadStringCompleted += RefreshCompleted;
        client.DownloadStringAsync(new Uri("http://sds.webs.pm/update.json"));
    }
    public override System.Collections.IEnumerator Execute(UTContext context)
    {
        if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.WebPlayer ||
            EditorUserBuildSettings.activeBuildTarget == BuildTarget.WebPlayerStreamed) {
            Debug.LogWarning("You have currently set the build target to 'Web Player'. This may cause interference with actions that access the internet. If you get an error message about cross domain policy from this action, switch the target to 'PC and Mac Standalone' and try again.");
        }

        var theNexusUrl = nexusUrl.EvaluateIn (context);
        if (string.IsNullOrEmpty (theNexusUrl)) {
            throw new UTFailBuildException ("You need to specify the nexus URL", this);
        }

        var theRepoId = repositoryId.EvaluateIn (context);
        if (string.IsNullOrEmpty (theRepoId)) {
            throw new UTFailBuildException ("You need to specify the repository id.", this);
        }

        var theUserName = userName.EvaluateIn (context);
        var thePassword = password.EvaluateIn (context);

        var theGroupId = groupId.EvaluateIn (context);
        if (string.IsNullOrEmpty (theGroupId)) {
            throw new UTFailBuildException ("You need to specify the group id.", this);
        }

        var theArtifactId = artifactId.EvaluateIn (context);
        if (string.IsNullOrEmpty (theArtifactId)) {
            throw new UTFailBuildException ("You need to specify the artifact id.", this);
        }

        var theVersion = version.EvaluateIn (context);
        if (string.IsNullOrEmpty (theVersion)) {
            throw new UTFailBuildException ("You need to specify the version.", this);
        }

        var thePackaging = packaging.EvaluateIn (context);
        if (string.IsNullOrEmpty (thePackaging)) {
            throw new UTFailBuildException ("You need to specify the packaging.", this);
        }

        var theExtension = extension.EvaluateIn (context);
        var theClassifier = classifier.EvaluateIn (context);

        var theInputFileName = inputFileName.EvaluateIn (context);
        if (string.IsNullOrEmpty (theInputFileName)) {
            throw new UTFailBuildException ("You need to specify the input file name.", this);
        }

        if (Directory.Exists (theInputFileName)) {
            throw new UTFailBuildException ("The specified input file " + theInputFileName + " is a directory.", this);
        }

        if (!File.Exists (theInputFileName)) {
            throw new UTFailBuildException ("The specified input file " + theInputFileName + " does not exist.", this);
        }

        WWWForm form = new WWWForm ();
        form.AddField ("r", theRepoId);
        form.AddField ("g", theGroupId);
        form.AddField ("a", theArtifactId);
        form.AddField ("v", theVersion);

        if (!string.IsNullOrEmpty (thePackaging)) {
            form.AddField ("p", thePackaging);
        }

        if (!string.IsNullOrEmpty (theClassifier)) {
            form.AddField ("c", theClassifier);
        }

        if (!string.IsNullOrEmpty (theExtension)) {
            form.AddField ("e", theExtension);
        }

        var bytes = File.ReadAllBytes (theInputFileName);
        form.AddBinaryData ("file", bytes, new FileInfo (theInputFileName).Name);

        var hash = UTils.ComputeHash (bytes);
        if (UTPreferences.DebugMode) {
            Debug.Log ("SHA1-Hash of file to upload: " + hash);
        }

        string authString = theUserName + ":" + thePassword;
        var authBytes = System.Text.UTF8Encoding.UTF8.GetBytes (authString);

        var headers = new Hashtable ();
        foreach (var key in form.headers.Keys) {
            headers.Add (key, form.headers [key]);
        }

        headers.Add ("Authorization", "Basic " + System.Convert.ToBase64String (authBytes));
        var url = UTils.BuildUrl (theNexusUrl, "/service/local/artifact/maven/content");
        using (var www = new WWW (url, form.data, headers)) {
            do {
                yield return "";
            } while(!www.isDone && !context.CancelRequested);

            if (UTPreferences.DebugMode) {
                Debug.Log ("Server Response: " + www.text);
            }
        }

        if (!context.CancelRequested) {

            using (var wc = new WebClient()) {

                if (!string.IsNullOrEmpty (theUserName)) {
                    Debug.Log("Setting credentials" );
                    wc.Credentials = new NetworkCredential (theUserName, thePassword);
                }

                Uri uri = new Uri (UTils.BuildUrl (theNexusUrl, "/service/local/artifact/maven/resolve?") +
            "g=" + Uri.EscapeUriString (theGroupId) +
            "&a=" + Uri.EscapeUriString (theArtifactId) +
            "&v=" + Uri.EscapeUriString (theVersion) +
            "&r=" + Uri.EscapeUriString (theRepoId) +
            "&p=" + Uri.EscapeUriString (thePackaging) +
            (!string.IsNullOrEmpty (theClassifier) ? "&c=" + Uri.EscapeUriString (theClassifier) : "") +
            (!string.IsNullOrEmpty (theExtension) ? "&e=" + Uri.EscapeUriString (theExtension) : ""));

                var downloadFinished = false;
                var error = false;
                string result = null;
                wc.DownloadStringCompleted += delegate( object sender, DownloadStringCompletedEventArgs e) {
                    downloadFinished = true;
                    error = e.Error != null;
                    if (error) {
                        Debug.LogError ("An error occured while downloading artifact information. " + e.Error.Message, this);
                    } else {
                        result = (string)e.Result;
                    }
                };

                wc.DownloadStringAsync (uri);

                do {
                    yield return "";
                    if (context.CancelRequested) {
                        wc.CancelAsync ();
                    }
                } while(!downloadFinished);

                if (!context.CancelRequested) {

                    if (!error) {
                        if (UTPreferences.DebugMode) {
                            Debug.Log ("Server Response: " + result);
                        }
                        if (result.Contains ("<sha1>" + hash + "</sha1>")) {
                            Debug.Log ("Successfully uploaded artifact " + theInputFileName + ".", this);
                        } else {
                            throw new UTFailBuildException ("Upload failed. Checksums do not match.", this);
                        }
                    } else {
                        throw new UTFailBuildException ("Artifact verification failed", this);
                    }
                }
            }
        }
    }
示例#49
-1
    private void CreateBodyPart(System.Uri meshUrl, System.Uri jpgUrl)
    {
        //download jpg and save into a jpg file.
        Debug.Log ("trying to load " + meshUrl.AbsoluteUri);
        WebClient webClient = new WebClient ();

        webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownCompleted);
        webClient.DownloadStringAsync (meshUrl);

        jpgUrlPath = jpgUrl;
    }