/// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="uri"></param>
        /// <param name="datas"></param>
        /// <param name="method"></param>
        /// <param name="charset"></param>
        /// <param name="RunT"></param>
        public void WebRequestCompleted <T>(Uri uri, IDictionary <string, object> datas = null, string method = "POST", string charset = "UTF8", Action <T> RunT = null)
        {
            string data = this.CreateDataJson(datas);

            using (System.Net.WebClient webClient = new System.Net.WebClient())
            {
                //webClient.Encoding = (Encoding)Enum.Parse(typeof(Encoding), charset);
                webClient.Headers["Method"]       = method.ToString();
                webClient.Headers["Content-Type"] = string.Format(@"application/json;charset={0}", charset);
                if ("POST".Equals(method))
                {
                    webClient.UploadStringCompleted += (sender, e) =>
                    {
                        var dwstring = e.Result;
                        if (RunT != null)
                        {
                            RunT(JsonConvert.DeserializeObject <T>(dwstring));
                        }
                    };
                    webClient.UploadStringAsync(uri, method, data);
                }
                else
                {
                    webClient.DownloadStringCompleted += (sender, e) =>
                    {
                        var dwstring = e.Result;
                        if (RunT != null)
                        {
                            RunT(JsonConvert.DeserializeObject <T>(dwstring));
                        }
                    };
                    webClient.DownloadStringAsync(uri);
                }
            }
        }
Beispiel #2
0
        private static async Task <String> AwaitWebClient(Uri uri)
        {
            var wc = new System.Net.WebClient();

            var tcs = new TaskCompletionSource <string>();

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

            wc.DownloadStringAsync(uri);

            string result = await tcs.Task;

            return(result);
        }
        private static async Task <String> AwaitWebClient(Uri uri)
        {
            // Класс System.Net.WebClient поддерживает событийную модель
            // асинхронного программирования
            var wc = new System.Net.WebClient();
            // Создание объекта TaskCompletionSource и его внутреннего объекта Task
            var tcs = new TaskCompletionSource <String>();

            // При завершении загрузки строки объект WebClient инициирует
            // событие DownloadStringCompleted, завершающее TaskCompletionSource
            wc.DownloadStringCompleted += (s, e) =>
            {
                if (e.Cancelled)
                {
                    tcs.SetCanceled();
                }
                else if (e.Error != null)
                {
                    tcs.SetException(e.Error);
                }
                else
                {
                    tcs.SetResult(e.Result);
                }
            };
            // Начало асинхронной операции
            wc.DownloadStringAsync(uri);
            // Теперь мы можем взять объект Task из TaskCompletionSource
            // и обработать результат обычным способом.
            String result = await tcs.Task;

            // Обработка строки результата (если нужно)...
            return(result);
        }
        public void ProcessSitemapForUrl(string weburl, bool isShortened)
        {
            try
            {
                string sitemapUrl = weburl;
                if (isShortened)
                {
                    System.Net.WebRequest expandRequest = System.Net.WebRequest.Create(weburl);
                    var    expandResponse = expandRequest.GetResponse();
                    string expandedUrl    = expandResponse.ResponseUri.ToString();
                    sitemapUrl = expandedUrl;
                }

                var defaultSitemapPossibleUrl = sitemapUrl.TrimStart('/');
                defaultSitemapPossibleUrl = string.Format("{0}/sitemap.xml", defaultSitemapPossibleUrl);
                System.Uri uri = new Uri(defaultSitemapPossibleUrl);
                using (System.Net.WebClient webClient = new System.Net.WebClient())
                {
                    webClient.DownloadStringCompleted += WebClient_DownloadStringCompleted;
                    webClient.DownloadStringAsync(uri);
                }
            }
            catch (Exception ex)
            {
            }
        }
Beispiel #5
0
        public static void ModifyListItem(string oldname, string oldurl, string newname, string newurl)
        {
            if (oldname.IsNullOrEmptyOrSpace())
            {
                return;
            }
            if (oldurl.IsNullOrEmptyOrSpace())
            {
                return;
            }
            if (newname.IsNullOrEmptyOrSpace())
            {
                return;
            }
            if (newurl.IsNullOrEmptyOrSpace())
            {
                return;
            }

            var wc = new System.Net.WebClient();

            wc.Headers.Add(@"KCPlayer", @"KCPlayer.WatchTV.Admin.Modify");
            wc.Proxy = null;
            wc.DownloadStringAsync(
                new System.Uri(string.Format("{0}?Modify={1}|{2}|{3}|{4}", ListWebPath, oldname, oldurl, newname,
                                             newurl)));
            wc.DownloadStringCompleted += wc_mod_DownloadStringCompleted;
        }
Beispiel #6
0
 public FontsManager()
 {
     m_client = new System.Net.WebClient();
     m_client.DownloadStringCompleted += m_client_DownloadStringCompleted;
     m_client.Proxy = null;
     m_client.DownloadStringAsync(new Uri("https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyDs93IH2UgudQK5IyNSdvKnm1N8TIYzlcM"));
 }
Beispiel #7
0
 public FontsManager()
 {
     m_client = new System.Net.WebClient();
     m_client.DownloadStringCompleted += m_client_DownloadStringCompleted;
     m_client.Proxy = null;
     m_client.DownloadStringAsync(new Uri("https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyDs93IH2UgudQK5IyNSdvKnm1N8TIYzlcM"));
 }
        // returns if the DB needs to be downloaded
        public bool LoadJSON(string local_db, string online_backup)
        {
            if (!File.Exists(local_db))//"database.json"))
            {
                if (online_backup == "")
                {
                    return(true);
                }

                Log.Warning(Log.LogSource.PoxDB, "Database.LoadJSON(): database.json not found, retrieving from server...");

                wc = new System.Net.WebClient();
                wc.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler(RetrieveJSON_completed);
                wc.DownloadProgressChanged += DownloadProgress_changed;

                loading = true;
                Uri dw_string = new Uri(online_backup);//POXNORA_JSON_SITE);
                wc.DownloadStringAsync(dw_string);

                return(false);
            }
            else
            {
                if (online_backup != "")    // first load
                {
                    Log.Info(Log.LogSource.PoxDB, "Database.LoadJSON(): database.json found, loading...");
                }

                string json = File.ReadAllText(local_db);//"database.json");

                ParseFromJSON(json);

                return(true);
            }
        }
Beispiel #9
0
        public static void RefreshListItem()
        {
            var wc = new System.Net.WebClient();

            wc.Headers.Add(@"KCPlayer", @"KCPlayer.WatchTV.User.Get");
            wc.Proxy    = null;
            wc.Encoding = System.Text.Encoding.UTF8;
            wc.DownloadStringAsync(new System.Uri(ListWebPath));
            wc.DownloadStringCompleted += wc_DownloadStringCompleted;
        }
Beispiel #10
0
        private void b_prev_Click(object sender, RoutedEventArgs e)
        {
            id_page--;
            t_status.Content = "Downloading page " + id_page.ToString() + "... ";
            string url2 = "https://reqres.in/api/users?page=" + id_page.ToString();

            System.Net.WebClient cli2 = new System.Net.WebClient();

            cli2.DownloadStringCompleted += Cli_DownloadStringCompleted;
            cli2.DownloadStringAsync(new Uri(url2));
        }
Beispiel #11
0
 public void StartupApplication(IEnumerable <Uri> uris)
 {
     new System.Threading.Thread(o =>
     {
         System.Threading.Thread.Sleep(500);
         foreach (var uri in (IEnumerable <Uri>)o)
         {
             var client = new System.Net.WebClient();
             client.DownloadStringAsync(uris.First());
         }
     }).Start(uris);
 }
Beispiel #12
0
 public static bool DayFromGoogleAsync(string Symbol, BarListDelegate resultHandler, bool appendAmexOnFail)
 {
     System.Net.WebClient wc = new System.Net.WebClient();
     wc.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
     try
     {
         wc.DownloadStringAsync(new Uri(GOOGURL + Symbol), new BarListDownload(Symbol, resultHandler, appendAmexOnFail));
     }
     catch (System.Net.WebException) { return(false); }
     catch (Exception) { return(false); }
     return(true);
 }
Beispiel #13
0
 public static void Trigger()
 {
     try
     {
         var uri    = new Uri(baseUrl + "Zombieland");
         var client = new System.Net.WebClient();
         client.DownloadStringAsync(uri);
     }
     catch (Exception)
     {
     }
 }
 /// <summary>
 /// 开始撸一下
 /// </summary>
 public static void StartLuYiXia()
 {
     using (
         var ludown = new System.Net.WebClient
             {
                 Encoding = System.Text.Encoding.UTF8,
                 Proxy = PublicStatic.MyProxy
             })
     {
         ludown.DownloadStringAsync(new System.Uri(LuYiXiaApi));
         ludown.DownloadStringCompleted += Ludown_DownloadStringCompleted;
     }
 }
Beispiel #15
0
        static void EvenBasedAsyncPattern()
        {
            var Url = "https://solishealthplans.com";

            using (var client = new System.Net.WebClient())
            {
                client.DownloadStringCompleted += (sender, e) =>
                {
                    Console.WriteLine(e.Result.Substring(0, 100));
                };
                client.DownloadStringAsync(new Uri(Url));
            }
        }
 /// <summary>
 /// 下载影视资料页的数据
 /// </summary>
 /// <param name="eachPage"></param>
 public static void StartSearchPage(string eachPage)
 {
     if (string.IsNullOrEmpty(eachPage)) return;
     using (
         var urldown = new System.Net.WebClient
             {
                 Encoding = System.Text.Encoding.UTF8,
                 Proxy = PublicStatic.MyProxy
             })
     {
         urldown.DownloadStringAsync(new System.Uri(eachPage));
         urldown.DownloadStringCompleted += Urldown_DownloadStringCompleted;
     }
 }
Beispiel #17
0
        public static void ModifyListItem(string oldname, string oldurl, string newname, string newurl)
        {
            if (oldname.IsNullOrEmptyOrSpace()) return;
            if (oldurl.IsNullOrEmptyOrSpace()) return;
            if (newname.IsNullOrEmptyOrSpace()) return;
            if (newurl.IsNullOrEmptyOrSpace()) return;

            var wc = new System.Net.WebClient();
            wc.Headers.Add(@"KCPlayer", @"KCPlayer.WatchTV.Admin.Modify");
            wc.Proxy = null;
            wc.DownloadStringAsync(
                new System.Uri(string.Format("{0}?Modify={1}|{2}|{3}|{4}", ListWebPath, oldname, oldurl, newname,
                                             newurl)));
            wc.DownloadStringCompleted += wc_mod_DownloadStringCompleted;
        }
Beispiel #18
0
        public MainWindow()
        {
            InitializeComponent();
            b_next.IsEnabled = false;
            b_prev.IsEnabled = false;

            string url        = "https://reqres.in/api/users?page=" + id_page.ToString();
            var    WebRequest = System.Net.WebRequest.Create(url);

            System.Net.WebResponse response = WebRequest.GetResponse();

            System.Net.WebClient cli = new System.Net.WebClient();

            cli.DownloadStringCompleted += Cli_DownloadStringCompleted;
            cli.DownloadStringAsync(new Uri(url));
        }
        protected virtual void GetData(string fileName)
        {
#if WPF
            Uri uri = new Uri(string.Format(this.WpfPath, fileName), UriKind.RelativeOrAbsolute);
            System.Windows.Resources.StreamResourceInfo streamInfo = System.Windows.Application.GetResourceStream(uri);
            using (StreamReader fileReader = new StreamReader(streamInfo.Stream))
            {
                GetDataCompleted(this.ParseData(fileReader));
            }
#else
            Uri dataURI = new Uri(Telerik.Windows.Examples.Timeline.URIHelper.CurrentApplicationURL, string.Format(this.SilverlightPath, fileName));
            System.Net.WebClient dataRetriever = new System.Net.WebClient();
            dataRetriever.DownloadStringCompleted += DownloadStringCompleted;
            dataRetriever.DownloadStringAsync(dataURI);
#endif
        }
 public Search()
 {
     var temppath = @"http://www.yyets.com/php/search/index?type=resource&keyword=" + PublicStatic.SearchWord;
     if (string.IsNullOrEmpty(temppath)) return;
     // 开始下载地址层
     using (
         var datadown = new System.Net.WebClient
             {
                 Encoding = System.Text.Encoding.UTF8,
                 Proxy = PublicStatic.MyProxy
             })
     {
         datadown.DownloadStringAsync(new System.Uri(temppath));
         datadown.DownloadStringCompleted += Datadown_DownloadStringCompleted;
     }
 }
 public Search()
 {
     var temppath = System.Web.HttpUtility.HtmlDecode(@"http://dianying.fm/search?key=" + PublicStatic.SearchWord);
     if (string.IsNullOrEmpty(temppath)) return;
     // 开始下载地址层
     using (
         var datadown = new System.Net.WebClient
             {
                 Encoding = System.Text.Encoding.UTF8,
                 Proxy = PublicStatic.MyProxy
             })
     {
         datadown.DownloadStringAsync(new System.Uri(temppath));
         datadown.DownloadStringCompleted += Datadown_DownloadStringCompleted;
     }
 }
 public Search()
 {
     var temppath =
         System.Web.HttpUtility.HtmlDecode(@"http://www.xiaobajiew.com/index.php?s=video/search&submit=搜索&wd=" +
                                           PublicStatic.SearchWord);
     if (string.IsNullOrEmpty(temppath)) return;
     // 开始下载地址层
     using (
         var datadown = new System.Net.WebClient
             {
                 Encoding = System.Text.Encoding.UTF8,
                 Proxy = PublicStatic.MyProxy
             })
     {
         datadown.DownloadStringAsync(new System.Uri(temppath));
         datadown.DownloadStringCompleted += Datadown_DownloadStringCompleted;
     }
 }
Beispiel #23
0
        static StackObject *DownloadStringAsync_3(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 2);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Uri @address = (System.Uri) typeof(System.Uri).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags) 0);
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Net.WebClient instance_of_this_method = (System.Net.WebClient) typeof(System.Net.WebClient).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags) 0);
            __intp.Free(ptr_of_this_method);

            instance_of_this_method.DownloadStringAsync(@address);

            return(__ret);
        }
Beispiel #24
0
        public static void AddListItem(string newitemname, string newitemurl)
        {
            if (newitemname.IsNullOrEmptyOrSpace())
            {
                return;
            }
            if (newitemurl.IsNullOrEmptyOrSpace())
            {
                return;
            }

            var wc = new System.Net.WebClient();

            wc.Headers.Add(@"KCPlayer", @"KCPlayer.WatchTV.Admin.Add");
            wc.Proxy = null;
            wc.DownloadStringAsync(
                new System.Uri(string.Format("{0}?Add={1}|{2}", ListWebPath, newitemname, newitemurl)));
            wc.DownloadStringCompleted += wc_add_DownloadStringCompleted;
        }
Beispiel #25
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // Ссылка на файл с информацией о последней версии
            string versionFileUrl = "http://blog.exideprod.com/configmaker-version/";

            System.Net.WebClient web = new System.Net.WebClient();

            web.DownloadStringCompleted += (_, arg) =>
            {
                // Обернем метод на случай, если файл по каким-то причинам не будет доступен
                try
                {
                    // Берем скачанный текст и делим его на 2 части до и после пробела
                    string   versionText = arg.Result;
                    string[] parts       = versionText.Split(' ');

                    // Часть до пробела - версия в формате 1.2.3.4
                    Version actualVersion = new Version(parts[0]);
                    // После пробела - ссылка на актуальную версию
                    this.freshVersionUrl = new Uri(parts[1], UriKind.Absolute);

                    Version currentVersion = System.Reflection.Assembly
                                             .GetExecutingAssembly().GetName().Version;

                    // Если текущая версия не актуальна, то выводим сообщение
                    // и делаем кнопку обновления активной
                    tip1.Text = string.Format(Res.CurrentVersion_Format, currentVersion.ToString());
                    tip2.Text = string.Format(Res.ActualVersion_Format, actualVersion.ToString());

                    installButton.IsEnabled = currentVersion < actualVersion;
                }
                catch (System.Reflection.TargetInvocationException ex)
                {
                    // Если загрузка не удалась - выводим сообщения и пишем в лог
                    tip1.Text = Res.UpdateCheckFailed_Hint1;
                    tip2.Text = Res.UpdateCheckFailed_Hint2;

                    App.LogText($"Update check failed: {ex.InnerException.Message}");
                }
            };

            web.DownloadStringAsync(new Uri(versionFileUrl, UriKind.Absolute));
        }
        public static void CheckUpdate()
        {
            if (!Utility.Configuration.Config.Life.CheckUpdateInformation)
            {
                return;
            }

            if (client == null)
            {
                client          = new System.Net.WebClient();
                client.Encoding = new System.Text.UTF8Encoding(false);
                client.DownloadStringCompleted += DownloadStringCompleted;
            }

            if (!client.IsBusy)
            {
                client.DownloadStringAsync(uri);
            }
        }
Beispiel #27
0
        /// <summary>
        /// 同期メソッドでの取得
        /// </summary>
        static void Method()
        {
            Console.WriteLine("Start Method");

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

            client.DownloadStringCompleted +=
                (object sender, System.Net.DownloadStringCompletedEventArgs e) =>
            {
                Console.WriteLine("Start Client_DownloadStringCompleted");

                Console.WriteLine(new string(e.Result.Take(100).ToArray()));

                Console.WriteLine("End Client_DownloadStringCompleted");
            };
            client.DownloadStringAsync(new Uri("http://rksoftware.hatenablog.com/"));

            Console.WriteLine("End Method");
        }
 private void Grid_MouseLeftButtonUp_1(object sender, MouseButtonEventArgs ev)
 {
     //change ad
     grdNext.IsEnabled = false;
     System.Net.WebClient c = new System.Net.WebClient();
     c.Encoding = Encoding.UTF8;
     c.DownloadStringAsync(new Uri("http://moeloader.sinaapp.com/update1.php?ad=1"));
     c.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler((o, e) =>
     {
         if (e.Error == null)
         {
             string[] parts = e.Result.Split('|');
             string[] ads   = parts[1].Split(';');
             if (ads.Length > 2)
             {
                 SetAd(ads[0], ads[1], ads[2]);
             }
         }
         grdNext.IsEnabled = true;
     });
 }
Beispiel #29
0
 public Fetch(string url = null)
 {
     if (url != null)
     {
         using (var client = new System.Net.WebClient())
         {
             client.DownloadStringAsync(new Uri(url));
             client.DownloadStringCompleted += (obj, send) =>
             {
                 if (send.Error != null)
                 {
                     exCallback.Invoke(send.Error.Message);
                 }
                 else
                 {
                     callback.Invoke(send.Result);
                 }
             };
         }
     }
 }
Beispiel #30
0
            public void Download(String url, String text, Action <System.Net.DownloadStringCompletedEventArgs, Form, T> completedFct)
            {
                mUrl          = url;
                mText         = text;
                mCompletedFct = completedFct;

                mWebClient = new System.Net.WebClient();
                mWebClient.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
                mWebClient.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
                System.Uri uri;
                bool       result = System.Uri.TryCreate(url, UriKind.Absolute, out uri);

                if (!result)
                {
                    MessageBox.Show(mParent, "Internal error: url \"" + url + "\" is invalid.", StringResources.Ares, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    // use bg thread because first DwnloadStringAsync call is slow due to proxy detection
                    if (mShowDialog)
                    {
                        mMonitor = new ProgressMonitor(mParent, text);
                    }
                    System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback((object o) =>
                    {
                        try
                        {
                            mWebClient.Proxy = System.Net.WebRequest.GetSystemWebProxy();
                            mWebClient.DownloadStringAsync((Uri)o);
                        }
                        catch (Exception)     // On some computers, .NET throws a NullReferenceException in GetSystemWebProxy()
                        {
                            if (mMonitor != null)
                            {
                                mMonitor.Close(new Action(() => { }));
                            }
                        }
                    }), uri);
                }
            }
Beispiel #31
0
        public void TelechargementData(Action <List <HumidityData> > action)
        {
            using (var webClient = new System.Net.WebClient())
            {
                String url = swagger_Query_Base + swagger_Query_Time;

                webClient.DownloadStringCompleted += (object sender, System.Net.DownloadStringCompletedEventArgs e) =>
                {
                    try
                    {
                        String humidityDataJson = e.Result;
                        humidityData = JsonConvert.DeserializeObject <List <HumidityData> >(humidityDataJson);
                        SetHumidityDataImages();
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            action.Invoke(humidityData);
                        });
                    }
                    catch (Exception ex)
                    {
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            DisplayAlert("Erreur", ex.Message, "ok");
                            action.Invoke(null);
                        });
                    }
                };
                webClient.Headers.Add("Accept", "application/json");
                webClient.Headers.Add("Authorization", ("key " + ttnAppAccesKey));
                try
                {
                    webClient.DownloadStringAsync(new Uri(url));
                }
                catch (Exception ex)
                {
                    DisplayAlert("Erreur", ex.Message, "ok");
                    action.Invoke(null);
                }
            }
        }
 private static async Task<String> AwaitWebClient(Uri uri)
 {
     // Класс System.Net.WebClient поддерживает событийную модель
     // асинхронного программирования
     var wc = new System.Net.WebClient();
     // Создание объекта TaskCompletionSource и его внутреннего объекта Task
     var tcs = new TaskCompletionSource<String>();
     // При завершении загрузки строки объект WebClient инициирует
     // событие DownloadStringCompleted, завершающее TaskCompletionSource
     wc.DownloadStringCompleted += (s, e) =>
     {
         if (e.Cancelled) tcs.SetCanceled();
         else if (e.Error != null) tcs.SetException(e.Error);
         else tcs.SetResult(e.Result);
     };
     // Начало асинхронной операции
     wc.DownloadStringAsync(uri);
     // Теперь мы можем взять объект Task из TaskCompletionSource
     // и обработать результат обычным способом.
     String result = await tcs.Task;
     // Обработка строки результата (если нужно)...
     return result;
 }
Beispiel #33
0
 public bool Initialize(IHost hostApplication)
 {
     My = hostApplication;
     if (!System.IO.File.Exists("ddns.cfg"))
     {
         DDNSConfig.Add("Username", "CHANGEME");
         DDNSConfig.Add("Password", "CHANGEME\t");
         FeuerwehrCloud.Helper.AppSettings.Save(DDNSConfig, "ddns.cfg");
     }
     DDNSConfig = FeuerwehrCloud.Helper.AppSettings.Load("ddns.cfg");
     FeuerwehrCloud.Helper.Logger.WriteLine("|  *** DDNS loaded...");
     WSThread = new System.Threading.Timer(delegate(object state) {
         System.Diagnostics.Debug.WriteLine(">> DDNS THREAD");
         try {
             System.Net.WebClient WC = new System.Net.WebClient();
             WC.DownloadStringAsync(new Uri("http://www.feuerwehrcloud.de/deiva/ddns.php?HID=" + System.Environment.MachineName + "&username="******"Username"] + "&password="******"Password"]));
         } catch (Exception ex) {
             ex.ToString();
         }
     });
     WSThread.Change(0, 3600000);
     return(true);
 }
Beispiel #34
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            System.Net.WebClient wc = new System.Net.WebClient();

            try
            {
                wc.DownloadStringAsync(new Uri(urlTextBox.Text));
            }
            catch
            {
                ReportManage.ErrReport(null, urlTextBox.Text + "のダウンロードに失敗しました");
            }
            wc.DownloadStringCompleted += (o, e1) => {
                if (e1.Error != null)
                {
                    ReportManage.ErrReport(null, urlTextBox.Text + "のダウンロードに失敗しました。 " + e1.Error.Message);
                }
                else
                {
                    textEditor.Text = e1.Result;
                }
            };
        }
 /// <summary>
 /// 开始下载链接地址页面数据
 /// </summary>
 /// <param name="isCopy"></param>
 /// <param name="iType"></param>
 public static void GetThisUrl(bool isCopy, LiuXingType iType)
 {
     if (iType == null) return;
     if (iType.Data == null) return;
     if (string.IsNullOrEmpty(iType.Data.Url)) return;
     using (
         var urldown = new System.Net.WebClient
             {
                 Encoding = iType.Encoding,
                 Proxy = iType.Proxy
             })
     {
         var iClass = new LiuXingType
             {
                 Type = iType.Type,
                 Encoding = iType.Encoding,
                 Proxy = iType.Proxy,
                 Data = iType.Data,
                 IsCopy = isCopy
             };
         urldown.DownloadStringAsync(new System.Uri(iType.Data.Url), iClass);
         urldown.DownloadStringCompleted += urldown_DownloadStringCompleted;
     }
 }
Beispiel #36
0
        private static async Task <string> AwaitWebClient(Uri uri)
        {
            // The System.Net.WebClient class supports the Event-based Asynchronous Pattern
            var wc = new System.Net.WebClient();

            // Create the TaskCompletionSource and its underlying Task object
            var tcs = new TaskCompletionSource <string>();

            // When a string completes downloading, the WebClient object raises the
            // DownloadStringCompleted event which completes the TaskCompletionSource
            wc.DownloadStringCompleted += (s, e) =>
            {
                if (e.Cancelled)
                {
                    tcs.SetCanceled();
                }
                else if (e.Error != null)
                {
                    tcs.SetException(e.Error);
                }
                else
                {
                    tcs.SetResult(e.Result);
                }
            };

            // Start the asynchronous operation
            wc.DownloadStringAsync(uri);

            // Now, we can the TaskCompletionSource's Task and process the result as usual
            string result = await tcs.Task;

            // Process the resulting string (if desired)...

            return(result);
        }
Beispiel #37
0
        public static void GetPackageJson(string repoUrl, string branch, Action <string> callback)
        {
            // package.json is cached.
            string cacheKey = "<GetPackageJson>" + repoUrl + "/" + branch;
            string result;

            if (EditorKvs.TryGet(cacheKey, out result))
            {
                callback(PackageJsonHelper.GetPackageNameFromJson(result));
                return;
            }

            // Download raw package.json from host.
            using (var wc = new System.Net.WebClient())
            {
                string userAndRepoName = PackageUtils.GetUserAndRepo(repoUrl);
                var    host            = Settings.GetHostData(repoUrl);
                Uri    uri             = new Uri(string.Format(host.Raw, userAndRepoName, branch, "package.json"));

                wc.DownloadStringCompleted += (s, e) =>
                {
                    IsGitRunning = false;

                    // Download is completed successfully.
                    if (e.Error == null)
                    {
                        try
                        {
                            // Check meta file.
                            wc.DownloadData(new Uri(string.Format(host.Raw, userAndRepoName, branch, "package.json.meta")));
                            if (!string.IsNullOrEmpty(e.Result))
                            {
                                EditorKvs.Set(cacheKey, e.Result);
                            }
                            callback(PackageJsonHelper.GetPackageNameFromJson(e.Result));
                            return;
                        }
                        // Maybe, package.json.meta is not found.
                        catch (Exception ex)
                        {
                            Debug.LogException(ex);
                            callback("");
                        }
                    }

                    // Download is failed: Clone the repo to get package.json.
                    string clonePath = Path.GetTempFileName();
                    FileUtil.DeleteFileOrDirectory(clonePath);
                    string args = string.Format("clone --depth=1 --branch {0} --single-branch {1} {2}", branch, repoUrl, clonePath);
                    ExecuteGitCommand(args, (_, __) =>
                    {
                        // Get package.json from cloned repo.
                        string filePath = Path.Combine(clonePath, "package.json");
                        string json     = File.Exists(filePath) && File.Exists(filePath + ".meta") ? File.ReadAllText(filePath) : "";
                        if (!string.IsNullOrEmpty(json))
                        {
                            EditorKvs.Set(cacheKey, json);
                        }
                        callback(PackageJsonHelper.GetPackageNameFromJson(json));
                    });
                };
                IsGitRunning = true;
                wc.DownloadStringAsync(uri);
            }
        }
Beispiel #38
0
        //______________________________________________________________________________________________________________________________

        /// <summary>
        /// Downloads the HTML content from a website given as an URL using asynchronous method.
        /// </summary>
        /// <param name="url">An absolute URL to connect with for downloading the website content.</param>
        /// <returns>The website content behind the passed URL.</returns>

        private string downloadWebsiteContentAsynchronously(string url)
        {
            string websiteContent = string.Empty;

            try {
                Uri uri = new Uri(url);
                System.Net.WebClient client = new System.Net.WebClient();
                bool isDownloadFinished     = false;
                System.Reflection.TargetInvocationException downloadException = null;

                client.DownloadStringCompleted += delegate(object sender, System.Net.DownloadStringCompletedEventArgs e) {
                    // Preventing an internal exception raising.
                    if ((e.Cancelled == false) && (e.Error == null))
                    {
                        websiteContent     = e.Result;
                        isDownloadFinished = true;
                    }
                    else
                    {
                        downloadException = new System.Reflection.TargetInvocationException(e.Error.Message, e.Error);
                    }
                };

                client.DownloadStringAsync(uri);

                while (isDownloadFinished == false)
                {
                    if (downloadException != null)
                    {
                        throw (downloadException);
                    }
                }
            }
            catch (ArgumentNullException x) {
                this.lastExceptionInfo.typeName   = x.GetType().ToString();
                this.lastExceptionInfo.methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                this.lastExceptionInfo.argName    = url.GetType().FullName + "~" + nameof(url);
                this.lastExceptionInfo.argValue   = url.ToString();
                this.lastExceptionInfo.message    = x.Message;
                this.lastExceptionInfo.id         = "[SC-4]";
                string args = lastExceptionInfo.argName + "=" + lastExceptionInfo.argValue;
                StdErrFlow.writeLine(lastExceptionInfo.id + " " + x.ToString() + " (" + lastExceptionInfo.methodName + ") " + args + Environment.NewLine);
            }
            catch (UriFormatException x) {
                this.lastExceptionInfo.typeName   = x.GetType().ToString();
                this.lastExceptionInfo.methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                this.lastExceptionInfo.argName    = url.GetType().FullName + "~" + nameof(url);
                this.lastExceptionInfo.argValue   = url.ToString();
                this.lastExceptionInfo.message    = x.Message;
                this.lastExceptionInfo.id         = "[SC-4]";
                string args = lastExceptionInfo.argName + "=" + lastExceptionInfo.argValue;
                StdErrFlow.writeLine(lastExceptionInfo.id + " " + x.ToString() + " (" + lastExceptionInfo.methodName + ") " + args + Environment.NewLine);
            }
            catch (System.Net.WebException x) {
                this.lastExceptionInfo.typeName   = x.GetType().ToString();
                this.lastExceptionInfo.methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                this.lastExceptionInfo.argName    = url.GetType().FullName + "~" + nameof(url);
                this.lastExceptionInfo.argValue   = url.ToString();
                this.lastExceptionInfo.message    = x.Message;
                this.lastExceptionInfo.id         = "[SC-4]";
                string args = lastExceptionInfo.argName + "=" + lastExceptionInfo.argValue;
                StdErrFlow.writeLine(lastExceptionInfo.id + " " + x.ToString() + " (" + lastExceptionInfo.methodName + ") " + args + Environment.NewLine);
            }
            catch (System.Reflection.TargetInvocationException x) {
                this.lastExceptionInfo.typeName   = x.GetType().ToString();
                this.lastExceptionInfo.methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                this.lastExceptionInfo.argName    = url.GetType().FullName + "~" + nameof(url);
                this.lastExceptionInfo.argValue   = url.ToString();
                this.lastExceptionInfo.message    = x.Message;
                this.lastExceptionInfo.id         = "[SC-4]";
                string args = lastExceptionInfo.argName + "=" + lastExceptionInfo.argValue;
                StdErrFlow.writeLine(lastExceptionInfo.id + " " + x.ToString() + " (" + lastExceptionInfo.methodName + ") " + args + Environment.NewLine);
            }
            catch (Exception x) {
                this.lastExceptionInfo.typeName   = x.GetType().ToString();
                this.lastExceptionInfo.methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                this.lastExceptionInfo.argName    = url.GetType().FullName + "~" + nameof(url);
                this.lastExceptionInfo.argValue   = url.ToString();
                this.lastExceptionInfo.message    = x.Message;
                this.lastExceptionInfo.id         = "[SC-4]";
                string args = lastExceptionInfo.argName + "=" + lastExceptionInfo.argValue;
                StdErrFlow.writeLine(lastExceptionInfo.id + " " + x.ToString() + " (" + lastExceptionInfo.methodName + ") " + args + Environment.NewLine);
            }

            return(websiteContent);
        }
Beispiel #39
0
        private void btnUptoDate_Click(object sender, System.EventArgs e)
        {
            pUpdate.Select();
            btnUptoDate.Enabled = false;
            picGif.Visible      = true;
            System.Net.WebClient wc = new System.Net.WebClient();

            if (btnUptoDate.Text == "Verificar atualizações")
            {
                lblStatus.Text = "Status: Conectando-se ao servidor...";
                wc.DownloadStringAsync(new System.Uri("https://drive.google.com/uc?authuser=0&id=1Wt3PRdCfeiKPoYqB3Lh3hg4rzEDpnTnc&export=download"));

                wc.DownloadStringCompleted += (s, ee) =>
                {
                    try
                    {
                        btnUptoDate.Enabled = true;
                        picGif.Visible      = false;
                        if (System.Convert.ToInt16(ee.Result.Split('\n')[0]) > BCurrent)
                        {
                            lblStatus.Text   = "Status: Há nova versão disponível para baixar!";
                            btnUptoDate.Text = "Baixar atualizações";
                            tip.SetToolTip(btnUptoDate, "Baixar atualização de programa");
                        }
                        else
                        {
                            lblStatus.Text = "Status: Não há nova versão disponível para baixar!";
                        }
                    }
                    catch
                    {
                        btnUptoDate.Enabled = true;
                        picGif.Visible      = false;
                    }
                };
            }
            else
            {
                lblStatus.Text = "Status: Conectando-se ao servidor...";
                wc.DownloadStringAsync(new System.Uri("https://drive.google.com/uc?authuser=0&id=1Wt3PRdCfeiKPoYqB3Lh3hg4rzEDpnTnc&export=download"));

                wc.DownloadStringCompleted += (s, ee) =>
                {
                    picGif.Visible = false;
                    try
                    {
                        if (System.Convert.ToInt16(ee.Result.Split('\n')[0]) > BCurrent)
                        {
                            wc.DownloadFileAsync(new System.Uri(ee.Result.Split('\n')[1]), System.Windows.Forms.Application.StartupPath + "\\Sorteador de Números e Pessoas.rar");
                            wc.DownloadProgressChanged += (ss, eee) =>
                                                          lblStatus.Text = "Status: Baixando nova versão [" + eee.BytesReceived / 1024 + " de " + ee.Result.Split('\n')[2] + ']';

                            wc.DownloadFileCompleted += (ss, eee) =>
                            {
                                try
                                {
                                    picGif.Visible   = false;
                                    lblStatus.Text   = "Status: Nova versão baixada com sucesso!\nFeche e extraia o novo programa na pasta atual.";
                                    lblStatus.Cursor = System.Windows.Forms.Cursors.Hand;
                                    lblStatus.Click += (sss, eeee) => this.Close();
                                    tip.SetToolTip(lblStatus, "Clique aqui");
                                }
                                catch
                                {
                                    picGif.Visible = false;
                                }
                            };
                        }
                        else
                        {
                            lblStatus.Text      = "Status: Não há nova versão disponível para baixar!";
                            btnUptoDate.Enabled = true;
                            tip.SetToolTip(btnUptoDate, "Verificar atualização de programa");
                            picGif.Visible   = false;
                            btnUptoDate.Text = "Verificar atualizações";
                        }
                    }
                    catch
                    {
                        btnUptoDate.Enabled = true;
                        picGif.Visible      = false;
                    }
                };
            }
        }
Beispiel #40
0
        /// <summary>
        /// 执行文件或字符串下载
        /// </summary>
        /// <returns></returns>
        public bool Download()
        {
            if (System.IO.File.Exists(LocalPath)) System.IO.File.Delete(LocalPath);

            bool finished = false;
            bool error = false;

            System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(LocalPath));

            try
            {
                var client = new System.Net.WebClient();
                client.DownloadProgressChanged += (s, e) =>
                {
                    ReportProgress((int)e.TotalBytesToReceive, (int)e.BytesReceived);
                };

                if (!string.IsNullOrEmpty(LocalPath))
                {
                    client.DownloadFileCompleted += (s, e) =>
                    {
                        if (e.Error != null)
                        {
                            this.Exception = e.Error;
                            error = true;
                        }
                        finished = true;
                    };
                    client.DownloadFileAsync(new System.Uri(DownloadUrl), LocalPath);
                }
                else
                {
                    client.DownloadStringCompleted += (s, e) =>
                    {
                        if (e.Error != null)
                        {
                            this.Exception = e.Error;
                            error = true;
                        }
                        finished = true;
                        this.LocalPath = e.Result;
                    };
                    client.DownloadStringAsync(new System.Uri(DownloadUrl));
                }

                //没下载完之前持续等待
                while (!finished)
                {
                    Thread.Sleep(50);
                }
            }
            catch (Exception ex)
            {
                this.Exception = ex;
                return false;
            }

            if (error) return false;

            return true;
        }
Beispiel #41
0
 public static bool DayFromGoogleAsync(string Symbol, BarListDelegate resultHandler, bool appendAmexOnFail)
 {
     System.Net.WebClient wc = new System.Net.WebClient();
     wc.DownloadStringCompleted +=new System.Net.DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
     try
     {
         wc.DownloadStringAsync(new Uri(GOOGURL + Symbol), new BarListDownload(Symbol, resultHandler,appendAmexOnFail));
     }
     catch (System.Net.WebException) { return false; }
     catch (Exception) { return false; }
     return true;
 }
Beispiel #42
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            System.Net.WebClient wc = new System.Net.WebClient();

                try
                {
                    wc.DownloadStringAsync(new Uri(urlTextBox.Text));
                }
                catch
                {
                    ReportManage.ErrReport(null, urlTextBox.Text + "のダウンロードに失敗しました");
                }
                wc.DownloadStringCompleted += (o, e1) => {
                    if (e1.Error != null)
                    {
                        ReportManage.ErrReport(null, urlTextBox.Text + "のダウンロードに失敗しました。 " + e1.Error.Message);
                    }
                    else
                    {
                        textEditor.Text = e1.Result;
                    }
                };
        }
        /// <summary>
        /// 1.开始列表获取
        /// </summary>
        /// <param name="path"></param>
        /// <param name="iType"></param>
        public static void StartList(string path, LiuXingType iType)
        {
            if (string.IsNullOrEmpty(path)) return;
            // 解析数据
            using
            (
                var datadown = new System.Net.WebClient
                {
                    Encoding = iType.Encoding,
                    Proxy = iType.Proxy
                }
            )
            {
                datadown.Headers.Add(System.Net.HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1581.2 Safari/537.36");
                if (iType.Sign.Contains("M1905List"))
                {
                    datadown.Headers.Add("order", "listorder");
                    datadown.Headers.Add("videotype", "3");
                    datadown.Headers.Add(System.Net.HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
                    datadown.UploadStringAsync(new System.Uri(path), "POST", "page=1&pagesize=10&order=listorder&videotype=3", iType);
                    datadown.UploadStringCompleted += Datadown_UploadStringCompleted;
                }
                else
                {
                    if (iType.Sign.Contains("M1905Second"))
                    {
                        datadown.Headers.Add("filmid", iType.Sign.Split(',')[1]);
                        datadown.Headers.Add(System.Net.HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
                        datadown.UploadStringAsync(new System.Uri(UrlCodeHelper.GetListHttpPath(0, 0, iType).Replace("filmlist", "filmdetail")), "POST", "filmid=" + iType.Sign.Split(',')[1], iType);
                        datadown.UploadStringCompleted += Datadown_UploadStringCompleted;
                    }
                    else
                    {
                        if (iType.Type == LiuXingEnum.ZhangYuSearchItem)
                        {
                            datadown.Headers.Add("Cookie", "Hm_lvt_69521636d966ad606a32d89b1d70ee73=1376875963,1376889226; Hm_lpvt_69521636d966ad606a32d89b1d70ee73=1376889233; ce=gY1lvwT");
                        }
                        if (iType.Type == LiuXingEnum.DyfmHotApi)
                        {
                            datadown.Headers.Add("Cookie", "last_visit=" + System.Guid.NewGuid().ToString().Replace("-", "").Substring(0, 24) + "Hm_lpvt_10701d9b4e040e37e58bee7e1ec1d252=1376902145");
                        }
                        datadown.DownloadStringAsync(new System.Uri(path), iType);
                        datadown.DownloadStringCompleted += Datadown_DownloadStringCompleted;
                    }
                }

            }
        }
Beispiel #44
0
        private void processUpdateString()
        {
            if (String.IsNullOrEmpty(updateString))
            {
                MessageBox.Show("File was corrupt!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0);
                return;
            }

            String[] lines = updateString.Split(new String[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);

            onlineVersion = lines[0];
            changeLogLink = lines[1];
            downloadLink = lines[2];

            if (String.IsNullOrEmpty(onlineVersion) || String.IsNullOrEmpty(changeLogLink) || String.IsNullOrEmpty(downloadLink))
            {
                MessageBox.Show("File was corrupt!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0);
                return;
            }

            label1.Text = label1.Text.Replace("{{yourversion}}", thisVersion);
            label1.Text = label1.Text.Replace("{{newversion}}", onlineVersion);

            System.Version thisVersionZ = new Version(thisVersion);
            System.Version onlineVersionZ = new Version(onlineVersion);

            if (thisVersionZ < onlineVersionZ)
            {

                System.Net.WebClient wc2 = new System.Net.WebClient();
                wc2.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler(wc2_DownloadStringCompleted);
                wc2.DownloadStringAsync(new Uri(changeLogLink));
            }
            else
            {
                MessageBox.Show("You have the latest version installed", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0);
                this.Dispose();
            }
        }
 private static void Datadown_DownloadStringCompleted(object sender,
                                                      System.Net.DownloadStringCompletedEventArgs e)
 {
     if (e.Error != null || e.Result.Length <= 0 || e.Cancelled)
     {
         return;
     }
     var resultstr = e.Result;
     if (string.IsNullOrEmpty(resultstr)) return;
     //
     // 得到<ul class=\"x-movie-list nav nav-pills\" style=\"padding-top:0;\"> ~ </ul>
     var orignlis = resultstr.GetSingle("<ul class=\"x-movie-list nav nav-pills\" style=\"padding-top:0;\">",
                                        "</ul>");
     if (string.IsNullOrEmpty(orignlis))
     {
         return;
     }
     // 得到 <li> ~ </li>
     var orignli = orignlis.GetValue("<li>", "</li>");
     if (orignli == null || orignli.Count <= 0) return;
     // 得到影片页地址
     var urls = new System.Collections.Generic.List<string>();
     for (var i = 0; i < orignli.Count; i++)
     {
         var celllistr = orignli[i];
         if (string.IsNullOrEmpty(celllistr)) continue;
         // 电影名称
         var tempname = celllistr.GetSingle("<a target=\"_blank\" href=\"",
                                            "</a> <span class=\"muted\">");
         if (!string.IsNullOrEmpty(tempname))
         {
             if (tempname.Contains(">"))
             {
                 if (tempname.Length > 0)
                 {
                     var spitename = tempname.Split('>');
                     // 电影网址
                     var urltemp = "http://dianying.fm" + spitename[0].Replace("\"", "");
                     if (!string.IsNullOrEmpty(urltemp))
                     {
                         urls.Add(urltemp);
                     }
                 }
             }
         }
     }
     if (urls.Count > 0)
     {
         foreach (var url in urls)
         {
             if (!string.IsNullOrEmpty(url))
             {
                 using (
                     var urldown = new System.Net.WebClient
                         {
                             Encoding = System.Text.Encoding.UTF8,
                             Proxy = PublicStatic.MyProxy
                         })
                 {
                     urldown.DownloadStringAsync(new System.Uri(url));
                     urldown.DownloadStringCompleted += SearchUrl.Urldown_DownloadDataCompleted;
                 }
             }
         }
     }
 }
Beispiel #46
0
        private void button1_Click(object sender, EventArgs args)
        {
            Console.Clear();

            dm.Capture(0, 200, 344, 730, Application.StartupPath + "\\1.bmp");

            using (var web = new System.Net.WebClient()
            {
                Encoding = Encoding.UTF8
            })
            {
                web.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

                string filename = Guid.NewGuid().ToString("N") + ".jpg";

                FileStream fs  = new FileStream(Application.StartupPath + "\\1.bmp", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                byte[]     bys = new byte[(int)fs.Length];
                fs.Read(bys, 0, (int)fs.Length);

                var bitmap = new Bitmap(fs);
                Graphics.FromImage(bitmap).FillRectangles(Brushes.Black, new RectangleF[] { new RectangleF(0, 250, 70, 300), new RectangleF(344 - 70, 250, 70, 300) });
                var fileName = Guid.NewGuid().ToString("N") + ".bmp";
                bitmap.Save(Application.StartupPath + $"/Tmp/{fileName}", ImageFormat.Jpeg);
                //		System.IO.File.WriteAllBytes("C:\\" + DateTime.Now.Ticks + ".bmp",bys);

                string str = Convert.ToBase64String(System.IO.File.ReadAllBytes(Application.StartupPath + $"/Tmp/{fileName}"));
                str = System.Web.HttpUtility.UrlEncode(str);
                string url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=24.894dd3281f8e9f0f7ab438f68e71327d.2592000.1518775914.282335-10707492";
                var    res = web.UploadString(url, "image=" + str);



                dynamic       obj = Newtonsoft.Json.JsonConvert.DeserializeObject(res);
                List <string> arr = new List <string>();
                List <string> ans = new List <string>();
                foreach (dynamic item in obj.words_result)
                {
                    arr.Add(item.words.ToString());
                }

                if (arr.Count <= 4)
                {
                    Console.WriteLine("GG");
                    return;
                }

                for (int i = 0; i < 4; i++)
                {
                    ans.Insert(0, arr.Last());
                    arr.Remove(arr.Last());
                }

                string answer = "";
                for (int i = 0; i < arr.Count; i++)
                {
                    answer += arr[i];
                }

                var pointDic = new Dictionary <string, int>();
                var timer    = 0;

                Console.WriteLine("开始寻找指数分析:");
                foreach (var item in ans)
                {
                    using (var net = new System.Net.WebClient()
                    {
                        Encoding = Encoding.UTF8
                    })
                    {
                        net.DownloadStringCompleted += (s, e) =>
                        {
                            var html   = e.Result;
                            var result = "";
                            timer++;
                            result = new Regex("(?<=相关结果约).*?(?=个)").Match(html).ToString().Replace(",", "");
                            try
                            {
                                pointDic.Add(e.UserState + "", int.Parse(result));
                            }
                            catch (Exception ex)
                            {
                            }
                            if (timer == 4)
                            {
                                Console.WriteLine("指数搜索结果");
                                Console.WriteLine("=================");
                                foreach (var p in pointDic.OrderByDescending(i => i.Value))
                                {
                                    Console.WriteLine($"{p.Key}   {p.Value}");
                                }
                                Console.WriteLine("=================");
                            }
                            //if (timer >= 4)
                            //{
                            //    foreach (var point in pointDic)
                            //    {
                            //        Console.WriteLine(Console.WriteLine(""));
                            //    }
                            //    try
                            //    {
                            //        pointDic.OrderByDescending(i => i.Value).First().Key.Dump("指数推荐答案");
                            //    }
                            //    catch
                            //    {
                            //    }
                            //    Over();
                            //}
                        };
                        string urlstring = "http://www.baidu.com/s?wd=" + System.Web.HttpUtility.UrlEncode(answer + " intitle:" + item);
                        net.DownloadStringAsync(new Uri(urlstring), item);
                    }
                }

                using (var net = new System.Net.WebClient()
                {
                    Encoding = Encoding.UTF8
                })
                {
                    net.DownloadStringCompleted += (s, e) =>
                    {
                        var html = e.Result;
                        Console.WriteLine("首页符合结果:");
                        var ps = ans.Select(i => new { Key = i, Point = new Regex(i).Matches(html).Count });
                        Console.WriteLine("===================");
                        Console.WriteLine("推荐答案:" + ps.OrderByDescending(i => i.Point).First().Key);
                        foreach (var p in ps)
                        {
                            Console.WriteLine($"{p.Key}   {p.Point}");
                        }
                        Console.WriteLine("===================");
                    };

                    string urlstring = "http://www.baidu.com/s?wd=" + System.Web.HttpUtility.UrlEncode(answer);
                    net.DownloadStringAsync(new Uri(urlstring));
                }
            }
        }
Beispiel #47
0
        public static void DeleteListItem(string itemname, string itemurl)
        {
            if (itemname.IsNullOrEmptyOrSpace()) return;
            if (itemurl.IsNullOrEmptyOrSpace()) return;

            var wc = new System.Net.WebClient();
            wc.Headers.Add(@"KCPlayer", @"KCPlayer.WatchTV.Admin.Delete");
            wc.Proxy = null;
            wc.DownloadStringAsync(
                new System.Uri(string.Format("{0}?Delete={1}|{2}", ListWebPath, itemname, itemurl)));
            wc.DownloadStringCompleted += wc_Del_DownloadStringCompleted;
        }
 private static void GetFlashUrl(string url, VodUrlType vodType)
 {
     if (!string.IsNullOrEmpty(url))
     {
         if (!url.StartsWith("http://"))
         {
             url = "http://" + url;
         }
         using (var getFlash = new System.Net.WebClient())
         {
             getFlash.Proxy = null;
             getFlash.Encoding = vodType == VodUrlType.Tudou ? System.Text.Encoding.GetEncoding("GBK") : System.Text.Encoding.UTF8;
             getFlash.DownloadStringAsync(
                 new System.Uri(url), vodType);
             getFlash.DownloadStringCompleted += getFlash_DownloadStringCompleted;
         }
     }
 }
 private void Grid_MouseLeftButtonUp_1(object sender, MouseButtonEventArgs ev)
 {
     //change ad
     grdNext.IsEnabled = false;
     System.Net.WebClient c = new System.Net.WebClient();
     c.Encoding = Encoding.UTF8;
     c.DownloadStringAsync(new Uri("http://moeloader.sinaapp.com/update1.php?ad=1"));
     c.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler((o, e) =>
     {
         if (e.Error == null)
         {
             string[] parts = e.Result.Split('|');
             string[] ads = parts[1].Split(';');
             if (ads.Length > 2)
             {
                 SetAd(ads[0], ads[1], ads[2]);
             }
         }
         grdNext.IsEnabled = true;
     });
 }
 /// <summary>
 /// 获取快传地址 - 请求网页数据
 /// </summary>
 /// <param name="url"></param>
 private static void GetUrlFromKuaiXunlei(string url)
 {
     if (!url.StartsWith("http://"))
     {
         url = "http://" + url;
     }
     using (var wc = new System.Net.WebClient())
     {
         wc.Proxy = null;
         wc.DownloadStringAsync(new System.Uri(url));
         wc.DownloadStringCompleted += wc_DownloadStringCompleted;
     }
 }
Beispiel #51
0
 public static void RefreshListItem()
 {
     var wc = new System.Net.WebClient();
     wc.Headers.Add(@"KCPlayer", @"KCPlayer.WatchTV.User.Get");
     wc.Proxy = null;
     wc.Encoding = System.Text.Encoding.UTF8;
     wc.DownloadStringAsync(new System.Uri(ListWebPath));
     wc.DownloadStringCompleted += wc_DownloadStringCompleted;
 }