/// <summary> /// 网络事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { if (e.Error != null) { RequestError(e.Error.Message); return; } if (ApiHelper.ContainsError(e.Result)) { ErrorMessage error = new ErrorMessage(); try { error = (ErrorMessage)JsonUtility.DeserializeObj( new MemoryStream(Encoding.UTF8.GetBytes(e.Result)), typeof(ErrorMessage)); RequestError(error.error_msg); } catch { RequestError("encoding error"); } } else { RequestComplete(e.Result); } }
public void DownloadStringAsync(Uri uri) { if (NetworkInterface.GetIsNetworkAvailable()) { try { WebClient downloader = new WebClient(); downloader.DownloadStringCompleted += ((s, a) => { try { if (DownloadStringCompleted != null) { DownloadStringCompletedEventArgs eventArg; if (a.Result == null || a.Error != null) eventArg = new DownloadStringCompletedEventArgs(new Exception(DownloadStringCompletedEventArgs.DOWNLOAD_FAILED)); else eventArg = new DownloadStringCompletedEventArgs(a.Result); System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate() { DownloadStringCompleted(this, eventArg); }); } } catch (WebException ex) { if (DownloadStringCompleted != null) { System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate() { DownloadStringCompleted(this, new DownloadStringCompletedEventArgs(new Exception(DownloadStringCompletedEventArgs.DOWNLOAD_EXCEPTION))); }); } } }); downloader.DownloadStringAsync(uri); } catch (Exception ex) { if (DownloadStringCompleted != null) { System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate() { DownloadStringCompleted(this, new DownloadStringCompletedEventArgs(new Exception(DownloadStringCompletedEventArgs.DOWNLOAD_EXCEPTION))); }); } } } else { if (DownloadStringCompleted != null) { System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate() { DownloadStringCompleted(this, new DownloadStringCompletedEventArgs(new Exception(DownloadStringCompletedEventArgs.NETWORK_UNAVAILABLE))); }); } } }
void wc_topic_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { string htmlPage = e.Result; System.Diagnostics.Debug.WriteLine("---------topic html---------"+sender.ToString()); System.Diagnostics.Debug.WriteLine(htmlPage); //string imgUrlPattern = "<img\\ssrc[^>]*jpg\">"; //for top head only //string topicUrlPattern = "<br><!--top:\\s\\d+--><li><a href=\"[^>]*html"; /*** * when verify regex with www.regexlib.com, use un-escaped expression, * otherwise it wont recognise. e.g: <!--top:\s\d+--><li><a href="[^>]*html * with \\s or \\d wont work. ***/ string topicUrlPattern = "<!--top:\\s\\d+--><li><a href=\"[^>]*html"; MatchCollection matches = Regex.Matches(htmlPage, topicUrlPattern, RegexOptions.IgnoreCase); topicPageCount = matches.Count; foreach (Match m in matches) { System.Diagnostics.Debug.WriteLine(m.ToString()); //BeginParseImageURL(m.ToString().Remove(0,34)); BeginParseImageURL(m.ToString().Remove(0,30)); //for test, to be save time by only get one topic. // break; } }
void DownCompleted(object sender, DownloadStringCompletedEventArgs e) { if(e!=null) this.json_data = e.Result; JSONNode parseJson = JSON.Parse (json_data); var verticesObjArr = parseJson["vertices"].AsArray; var uvObjArr = parseJson["uv"].AsArray; var facesObjArr = parseJson["faces"].AsArray; float[] verticesArr = new float[verticesObjArr.Count]; float[] uvArr = new float[uvObjArr.Count]; int[] facesArr = new int[facesObjArr.Count]; for(int v = 0; v<verticesArr.Length; v++) { verticesArr[v] = verticesObjArr[v].AsFloat; } for(int u = 0; u<uvArr.Length; u++) { uvArr[u] = uvObjArr[u].AsFloat; } for(int f = 0; f<facesArr.Length; f++) { facesArr[f] = facesObjArr[f].AsInt; } int numVertices = verticesArr.Length / 3; Vector3[] Vertex = new Vector3[numVertices]; for(int v=0; v<numVertices; v++) { Vertex[v] = new Vector3(verticesArr[0+ v*3], verticesArr[1 + v*3], verticesArr[2+ v*3]); } int numUVs = uvArr.Length / 2; Vector2[] UV_MaterialDisplay = new Vector2[numUVs]; for(int u=0; u<numUVs; u++) { UV_MaterialDisplay[u] = new Vector2(uvArr[0+ u*2], uvArr[1 + u*2]); } int[] Triangles = facesArr; this.Vertex = Vertex; this.UV_MaterialDisplay = UV_MaterialDisplay; this.Triangles = Triangles; load_mesh = true; }
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { if (e.Error == null) { if (DownloadStringCompleted != null) { System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate() { DownloadStringCompleted(this, new DownloadStringCompletedEventArgs(e.Result)); }); } } else { System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate() { DownloadStringCompleted(this, new DownloadStringCompletedEventArgs(new Exception("error"))); }); } }
public void TechNetBlogDownloadComplete(object sender, DownloadStringCompletedEventArgs e) { var client = sender as WebClient; if (client != null) { client.DownloadStringCompleted -= TechNetBlogDownloadComplete; } if (e.Error != null) { return; //throw e.Error; } if (e.Error == null && e.Result != null) { try { var xmlElement = XElement.Parse(e.Result); //String test = xmlElement.Elements("channel").Elements("item").Elements("title").First().Value; //MessageBox.Show(test); List <BlogItemModel> TechNetList = (from item in xmlElement.Elements("status") select new BlogItemModel { ItemUser = GetChildElementValue(item, "user", "screen_name"), ItemLink = GetChildElementValue(item, "user", "url"), ItemDisplayUser = GetChildElementValue(item, "user", "name"), ItemText = (string)item.Element("text"), ItemDate = GetCreatedDate((string)item.Element("created_at")), ItemImage = GetChildElementValue(item, "user", "profile_image_url"), ItemLocation = GetChildElementValue(item, "user", "location"), ItemDetail = GetChildElementValue(item, "user", "description"), ItemFollowers = "粉丝:" + GetChildElementValue(item, "user", "followers_count"), ItemFriends = "关注:" + GetChildElementValue(item, "user", "friends_count"), ItemBlogCount = "微博:" + GetChildElementValue(item, "user", "statuses_count"), Itemthumbnail = (string)item.Element("thumbnail_pic"), ItemOriginalpic = (string)item.Element("original_pic"), ReItemUser = GetThirdElementValue(item, "retweeted_status", "user", "text"), ReItemDisplayUser = GetThirdElementValue(item, "retweeted_status", "user", "name"), ReItemText = GetChildElementValue(item, "retweeted_status", "text"), ReItemMergedText = GetReTweetedText(GetThirdElementValue(item, "retweeted_status", "user", "name"), GetChildElementValue(item, "retweeted_status", "text")), ReItemDate = GetCreatedDate(GetChildElementValue(item, "retweeted_status", "created_at")), ReItemImage = GetChildElementValue(item, "retweeted_status", "thumbnail_pic"), ReItemOriginalpic = GetChildElementValue(item, "retweeted_status", "original_pic"), BlogId = (long)item.Element("id"), IsNewBlog = true, }).ToList(); BaseHelper.SaveSetting(Constants.TechNetBlogFileName, TechNetList); } catch (Exception ex) { //MessageBox.Show(ex.Message); Debug.WriteLine(ex.Message); } if (LoadedCompleteEvent != null) { LoadedCompleteEvent(this, EventArgs.Empty); } } }
static void DownloadStringCompletd(object sender, DownloadStringCompletedEventArgs weatherEventArgs) { string WeatherJSON = weatherEventArgs.Result; Console.WriteLine(WeatherJSON); }
protected override void OnDownloadStringCompleted(DownloadStringCompletedEventArgs e) { base.OnDownloadStringCompleted(e); }
/// <summary> /// DownloadStringCompleted event handler /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void StringDownloadCompleted(object sender, DownloadStringCompletedEventArgs e) { rssTextView.Text = e.Result.ToString(); progressDialog.Hide(); rssButton.Enabled = true; }
void userfiles_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { kbsellgasbusy.IsBusy = false; busy.IsBusy = false; if (e.Error != null) { MessageBox.Show("未找到用户的表具信息,请去表具建档!"); return; } //把数据转换成JSON JsonObject item = JsonValue.Parse(e.Result) as JsonObject; //把用户数据写到交费界面上 ui_username.Text = (string)item["f_username"]; ui_usertype.Text = (String)item["f_usertype"]; ui_districtname.Text = (String)item["f_districtname"]; ui_gasproperties.Text = (String)item["f_gasproperties"]; ui_stairpricetype.Text = (String)item["f_stairtype"]; // zhye.Text = item["f_zhye"].ToString(); ui_address.Text = (String)item["f_address"]; //ui_gaspricetype.Text = (String)item["f_gaspricetype"]; ui_userid.Text = item["infoid"].ToString(); //zhe.Text=item["f_zherownum"].ToString(); //ui_dibaohu.IsChecked = item["f_dibaohu"].ToString().Equals("1"); //ui_userstate.Text = (String)item["f_userstate"]; // ui_paytype.Text = (String)item["f_payment"]; // ui_gasprice.Text = item["f_gasprice"].ToString(); //把欠费数据插入到欠费表中 BaseObjectList list = dataGrid1.ItemsSource as BaseObjectList; if (list != null) { list.Clear(); } // 当前正在处理的表号 String currentId = ""; // 总的上期指数 decimal lastnum = 0; // 总气量 decimal gasSum = 0; // 总气费 decimal feeSum = 0; //总的滞纳金 decimal zhinajinAll = 0; //余额 decimal f_zhye = decimal.Parse(item["f_zhye"].ToString()); JsonArray bills = item["f_hands"] as JsonArray; foreach (JsonObject json in bills) { GeneralObject go = new GeneralObject(); go.EntityType = "t_handplan"; //默认选中 go.IsChecked = true; //上期指数 decimal lastinputgasnum = (decimal)json["lastinputgasnum"]; go.SetPropertyValue("lastinputgasnum", lastinputgasnum, false); string f_userid = (string)json["f_userid"]; go.SetPropertyValue("f_userid", f_userid, false); // 如果表号变了 if (!f_userid.Equals(currentId)) { currentId = f_userid; lastnum += lastinputgasnum; } //计算总金额 decimal oughtfee = (decimal)json["oughtfee"]; go.SetPropertyValue("oughtfee", oughtfee, false); feeSum += oughtfee; // 计算总气量 decimal oughtamount = (decimal)json["oughtamount"]; gasSum += oughtamount; go.SetPropertyValue("oughtamount", oughtamount, false); //计算总滞纳金 decimal f_zhinajin = (decimal)json["f_zhinajin"]; zhinajinAll += f_zhinajin; go.SetPropertyValue("f_zhinajin", f_zhinajin, false); int id = Int32.Parse(json["id"] + ""); go.SetPropertyValue("id", id, false); go.SetPropertyValue("lastinputdate", DateTime.Parse(json["lastinputdate"]), false); go.SetPropertyValue("lastrecord", (decimal)json["lastrecord"], false); go.SetPropertyValue("f_endjfdate", DateTime.Parse(json["f_endjfdate"]), false); go.SetPropertyValue("f_zhinajintianshu", (int)json["days"], false); go.SetPropertyValue("f_network", (string)json["f_network"], false); go.SetPropertyValue("f_operator", (string)json["f_operator"], false); go.SetPropertyValue("f_inputdate", DateTime.Parse(json["f_inputdate"]), false); go.SetPropertyValue("f_userid", (string)json["f_userid"], false); go.SetPropertyValue("f_stair1amount", (decimal)json["f_stair1amount"], false); go.SetPropertyValue("f_stair1price", (decimal)json["f_stair1price"], false); go.SetPropertyValue("f_stair1fee", (decimal)json["f_stair1fee"], false); go.SetPropertyValue("f_stair2amount", (decimal)json["f_stair2amount"], false); go.SetPropertyValue("f_stair2price", (decimal)json["f_stair2price"], false); go.SetPropertyValue("f_stair2fee", (decimal)json["f_stair2fee"], false); go.SetPropertyValue("f_stair3amount", (decimal)json["f_stair3amount"], false); go.SetPropertyValue("f_stair3price", (decimal)json["f_stair3price"], false); go.SetPropertyValue("f_stair3fee", (decimal)json["f_stair3fee"], false); list.Add(go); } }
/// <summary> /// Builds the pool data and starts the image-downloading threads /// </summary> private void DataClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { var dataToken = (DownloadDataToken)e.UserState; labelStatus.Text = "Building image list"; using (JsonReader reader = new JsonTextReader(new StringReader(e.Result))) { JsonSerializer serializer = new JsonSerializer(); var json = (JObject)serializer.Deserialize(reader); JToken t = null; if (json.TryGetValue("success", out t) || t != null && t.Value <bool> () == false) { progressBarStatus.Value = 0; labelStatus.Text = "Invalid pool"; gridControls.IsEnabled = true; return; } int pages = (int)(Math.Ceiling(((float)json ["post_count"]) / 24.0f)); List <JToken> posts = new List <JToken> (json ["posts"].AsJEnumerable()); if (pages > 1) { for (int i = 2; i < pages + 1; i++) { using (WebClient c = new WebClient()) { c.QueryString.Clear(); c.QueryString.Add("id", dataToken.PoolID); c.QueryString.Add("page", i.ToString()); SetHeaders(c.Headers); var str = c.DownloadString(new Uri(PoolAPIURL)); using (JsonReader r = new JsonTextReader(new StringReader(str))) { JObject j = (JObject)serializer.Deserialize(r); if (j.TryGetValue("success", out t) || t != null && t.Value <bool> () == false) { progressBarStatus.Value = 0; labelStatus.Text = "Invalid pool"; gridControls.IsEnabled = true; return; } posts.AddRange(j ["posts"].AsJEnumerable()); } } } } if (Properties.Settings.Default.DownloadInSubfolder) { string poolName = json ["name"].ToString().Replace('_', ' '); while (String.IsNullOrWhiteSpace(poolName) || Path.GetInvalidFileNameChars().Any(invChar => poolName.Contains(invChar))) // If the filename contains any invalid characters, ask the user to input a new name. { poolName = InputBox.ShowInputBox("Invalid pool name", "The pool name is empty or whitespace or contains illegal characters.\nPlease input a name for the pool folder", poolName); if (poolName == null) { progressBarStatus.Value = 0; labelStatus.Text = String.Format("Cancelled downloading pool {0} ({1})", dataToken.PoolID, json ["name"].ToString().Replace('_', ' ')); gridControls.IsEnabled = true; return; } } dataToken.PoolName = poolName; dataToken.DownloadPath = Path.Combine(dataToken.DownloadPath, poolName); } dataToken.ImageCount = posts.AsJEnumerable().Count(); dataToken.DownloadCount = 0; progressBarStatus.Value = 0; labelStatus.Text = String.Format("Downloading images - 1/{0}", dataToken.ImageCount); if (!Directory.Exists(dataToken.DownloadPath)) { Directory.CreateDirectory(dataToken.DownloadPath); } var threadTokens = new DownloaderThreadToken [ThreadCount]; var tasks = new Task [ThreadCount]; for (int i = 0; i < ThreadCount; i++) { threadTokens [i] = new DownloaderThreadToken(token); tasks [i] = new Task(new Action <object> (DoDownloadImages), threadTokens [i]); } for (int i = 0, threadNum = 0; i < posts.Count(); i++, threadNum++) { var post = posts [i]; if (threadNum >= threadTokens.Count()) { threadNum = 0; } var img = new e621ImageData(); img.Number = i; if (Properties.Settings.Default.StartAtOne) { img.Number += 1; } img.URL = post ["file_url"].ToString(); img.Filename = post ["md5"].ToString(); img.Extension = post ["file_ext"].ToString(); threadTokens [threadNum].ImageLinks.Add(img); } foreach (var task in tasks) { task.Start(); } } }
static void objClient_DownloadStringCompleted (object objSender, DownloadStringCompletedEventArgs e) { _result = e.Result; _complete = true; }
void _jump_webclient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { if (e.Error == null) { Output("成功获得jump文件 " + e.Result); Output("解析xml"); try { using (XmlReader reader = XmlReader.Create(new StringReader(e.Result))) { if (true == reader.ReadToFollowing("server_host")) { string server_host = reader.ReadElementContentAsString("server_host", ""); _media_server_host = server_host; Output("server_host=" + server_host); } else { // } reader.ReadToFollowing("server_time"); string server_time = reader.ReadElementContentAsString("server_time", ""); Output("server_time=" + server_time); CultureInfo ci = new CultureInfo("en-US"); _server_base_time = DateTime.ParseExact(server_time, "ddd MMM dd HH:mm:ss yyyy UTC", ci); _local_base_time = DateTime.Now; Output("_server_base_time=" + _server_base_time); _playDecodeUrl = "http://" + _media_server_host + ":80/" + _playInfo.Rid + "?type=wp7&w=1&key=" + GetServerRelativeTimeString(); Dispatcher.BeginInvoke(() => { xMedia.Source = new Uri(_playDecodeUrl, UriKind.Absolute); }); Output("播放地址:" + _playDecodeUrl); } } catch (Exception exp) { Output("jump_webclient_DownloadStringCompleted " + exp.ToString()); if (MediaFailed != null) { PPLiveExceptionRoutedEventArgs args = new PPLiveExceptionRoutedEventArgs(this, new PPLiveOpenException("获得jump文件失败 " + exp.Message)); MediaFailed(this, args); } } } else { Output("获得jump文件失败 " + e.Error.ToString()); if (MediaFailed != null) { PPLiveExceptionRoutedEventArgs args = new PPLiveExceptionRoutedEventArgs(this, new PPLiveOpenException("获得jump文件失败 " + e.Error.Message)); MediaFailed(this, args); } } }
protected virtual void OnDownloadStringCompleted ( DownloadStringCompletedEventArgs args) { if (DownloadStringCompleted != null) DownloadStringCompleted (this, args); }
public static void ShowComplete(object sender, DownloadStringCompletedEventArgs e) { if (e.Result != "") { Debug.Log("Page found!"); } else { return; } if (e.Result.Contains("LichtSensor")) { int indexPin = e.Result.IndexOf("LichtSensor"); string tempString = e.Result.Substring(indexPin + "LichtSensor".Length+2,1); SetLightValue(int.Parse(tempString)); } if (e.Result.Contains("TemperatuurSensor")) { int indexSensor = e.Result.IndexOf("TemperatuurSensor"); string tempString = e.Result.Substring(indexSensor + "TemperatuurSensor".Length + 2, 1); SetTemperatureValue(int.Parse(tempString)); } }
/// <summary> /// Parse YouTube API response to get video data (title, image, link). /// </summary> private void OnDownloadYoutubeApiCompleted(object sender, DownloadStringCompletedEventArgs e) { try { if (!e.Cancelled) { if (e.Error == null) { var idx = e.Result.IndexOf("\"media$title\"", StringComparison.Ordinal); if (idx > -1) { idx = e.Result.IndexOf("\"$t\"", idx); if (idx > -1) { idx = e.Result.IndexOf('"', idx + 4); if (idx > -1) { var endIdx = e.Result.IndexOf('"', idx + 1); while (e.Result[endIdx - 1] == '\\') { endIdx = e.Result.IndexOf('"', endIdx + 1); } if (endIdx > -1) { this._videoTitle = e.Result.Substring(idx + 1, endIdx - idx - 1).Replace("\\\"", "\""); } } } } idx = e.Result.IndexOf("\"media$thumbnail\"", StringComparison.Ordinal); if (idx > -1) { var iidx = e.Result.IndexOf("sddefault", idx); if (iidx > -1) { if (string.IsNullOrEmpty(Width)) { Width = "640px"; } if (string.IsNullOrEmpty(Height)) { Height = "480px"; } } else { iidx = e.Result.IndexOf("hqdefault", idx); if (iidx > -1) { if (string.IsNullOrEmpty(Width)) { Width = "480px"; } if (string.IsNullOrEmpty(Height)) { Height = "360px"; } } else { iidx = e.Result.IndexOf("mqdefault", idx); if (iidx > -1) { if (string.IsNullOrEmpty(Width)) { Width = "320px"; } if (string.IsNullOrEmpty(Height)) { Height = "180px"; } } else { iidx = e.Result.IndexOf("default", idx); if (string.IsNullOrEmpty(Width)) { Width = "120px"; } if (string.IsNullOrEmpty(Height)) { Height = "90px"; } } } } iidx = e.Result.LastIndexOf("http:", iidx, StringComparison.Ordinal); if (iidx > -1) { var endIdx = e.Result.IndexOf('"', iidx); if (endIdx > -1) { this._videoImageUrl = e.Result.Substring(iidx, endIdx - iidx).Replace("\\\"", "\"").Replace("\\", ""); } } } idx = e.Result.IndexOf("\"link\"", StringComparison.Ordinal); if (idx > -1) { idx = e.Result.IndexOf("http:", idx); if (idx > -1) { var endIdx = e.Result.IndexOf('"', idx); if (endIdx > -1) { this._videoLinkUrl = e.Result.Substring(idx, endIdx - idx).Replace("\\\"", "\"").Replace("\\", ""); } } } } else { HandleDataLoadFailure(e.Error, "YouTube"); } } } catch (Exception ex) { HtmlContainer.ReportError(HtmlRenderErrorType.Iframe, "Failed to parse YouTube video response", ex); } HandlePostApiCall(sender); }
private static void Client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { Console.WriteLine("Async code Download complete"); Console.WriteLine(e.Result.Substring(0, 100)); Console.WriteLine("Completed async download"); }
private void RequestCompleted(object sender, DownloadStringCompletedEventArgs e) { String statusText; if (e.Cancelled) { errors++; statusText = "Send timeout"; } else if (e.Error == null) { coordinateList.RemoveRange(0, sendOffset); sendOffset = 0; successful++; statusText = e.Result; } else { errors++; statusText = e.Error.Message; } mainPage.UpdateStatusDisplay(successful, errors, discarded, statusText); }
static void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { string[] lines = e.Result.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); tradeUpdater.UpdateTradeData(lines); }
//************************************************************************************************************* private void Client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { File.WriteAllText("oui.txt", e.Result); Start(); }
private void http_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { try { List <string> lines = ParseResult(e.Result); if (lines.Count == 0) { throw new Exception("Empty GFWList"); } if (File.Exists(USER_RULE_FILE)) { string local = File.ReadAllText(USER_RULE_FILE, Encoding.UTF8); string[] rules = local.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (string rule in rules) { if (rule.StartsWith("!") || rule.StartsWith("[")) { continue; } lines.Add(rule); } } string abpContent = gfwlist_template; if (File.Exists(USER_ABP_FILE)) { abpContent = File.ReadAllText(USER_ABP_FILE, Encoding.UTF8); } else { abpContent = gfwlist_template; } abpContent = abpContent.Replace("__RULES__", SimpleJson.SimpleJson.SerializeObject(lines)); if (File.Exists(PAC_FILE)) { string original = File.ReadAllText(PAC_FILE, Encoding.UTF8); if (original == abpContent) { update_type = 0; UpdateCompleted(this, new ResultEventArgs(false)); return; } } File.WriteAllText(PAC_FILE, abpContent, Encoding.UTF8); if (UpdateCompleted != null) { update_type = 0; UpdateCompleted(this, new ResultEventArgs(true)); } } catch (Exception ex) { if (Error != null) { WebClient http = sender as WebClient; if (http.BaseAddress.StartsWith(GFWLIST_URL)) { http.BaseAddress = GFWLIST_BACKUP_URL; http.DownloadStringAsync(new Uri(GFWLIST_BACKUP_URL + "?rnd=" + Util.Utils.RandUInt32().ToString())); } else { if (e.Error != null) { Error(this, new ErrorEventArgs(e.Error)); } else { Error(this, new ErrorEventArgs(ex)); } } } } }
/// <summary> /// Initializes a new instance of the <see cref="T:Geocrest.Model.WrappedDownloadStringCompletedEventArgs" /> class. /// </summary> /// <param name="args">The <see cref="T:System.Net.DownloadStringCompletedEventArgs" /> instance containing the event data.</param> public WrappedDownloadStringCompletedEventArgs(DownloadStringCompletedEventArgs args) : base(args, typeof(string), args.Error == null ? args.Result : string.Empty) { this.Result = args.Error == null ? args.Result : null; }
private void WB_DownStringCompleted(object sender, DownloadStringCompletedEventArgs e) { textBox1.Text = e.Result; }
void OnLatestChaptersTransferCompleted(object sender, DownloadStringCompletedEventArgs e) { if (null != e.Error) { _waitHandle.Set(); return; } try { List <MangaAbstractModel> latestChapters = JsonConvert.DeserializeObject <List <MangaAbstractModel> >(e.Result); foreach (MangaAbstractModel chapter in latestChapters) { chapter.IsRecentChapter = true; } // TODO: Is there a more efficient way to empty the entire table? // LINQ on Windows Phone doesn't seem to have ExecuteCommand(). var query = from MangaAbstractModel chapter in _mangaDB.Chapters where chapter.IsRecentChapter == true select chapter; _mangaDB.Chapters.DeleteAllOnSubmit(query); _mangaDB.SubmitChanges(); _mangaDB.Chapters.InsertAllOnSubmit(latestChapters); _mangaDB.SubmitChanges(); if (latestChapters.Count > 0) { string oldMangaId = string.Empty; if (IsolatedStorageSettings.ApplicationSettings.Contains(Constants._latestMangaId)) { oldMangaId = (string)IsolatedStorageSettings.ApplicationSettings[Constants._latestMangaId]; } if (!oldMangaId.Equals(latestChapters[0].MangaId)) { int releaseCount = 0; // Figure out how many new releases there are foreach (MangaAbstractModel model in latestChapters) { if (model.MangaId.Equals(oldMangaId)) { break; } else { releaseCount++; } } // Launch a toast to show that the agent is running. // The toast will not be shown if the foreground application is running. ShellToast toast = new ShellToast(); toast.Title = releaseCount > 1 ? "New manga releases" : "New manga release"; toast.Content = ""; toast.Show(); ShellTile appTile = ShellTile.ActiveTiles.First(); if (appTile != null) { StandardTileData tileData = new StandardTileData(); tileData.BackTitle = "MangaStream"; tileData.BackContent = releaseCount > 1 ? "New manga releases" : "New manga release"; tileData.Count = releaseCount; appTile.Update(tileData); } } IsolatedStorageSettings.ApplicationSettings[Constants._latestMangaId] = latestChapters[0].MangaId; IsolatedStorageSettings.ApplicationSettings.Save(); } } catch (Exception) { } finally { _waitHandle.Set(); } }
private void Web_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { throw new NotImplementedException(); }
private void Client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { _logger.LogMessage("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"); _logger.LogMessage(e.Result.Substring(0, 50)); _logger.LogMessage(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); }
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { richEdit1.RtfText = e.Result; }
private void WebClientDownloadCompleted(object sender, DownloadStringCompletedEventArgs e) { this.html = e.Result; progCompleted(this.html); }
private void mwc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { MyWebClient tmpmwc = (MyWebClient)sender; mwc[tmpmwc.mwcindex].timer.Stop(); mwc[tmpmwc.mwcindex].timer.Interval = 1000.0 * timeout; if (Interrupt) { mwc[tmpmwc.mwcindex].Dispose(); mwc[tmpmwc.mwcindex] = null; mtmwcRunningCheck.WaitOne(-1); mwcRunningCount--; RenewNodeCount--; Logging.Debug(String.Format("mwcRunningCount {0} RenewNodeCount {1}", mwcRunningCount, RenewNodeCount)); if (mwcRunningCount == 0 && RenewNodeCount == 0) { InProcessing = false; } mtmwcRunningCheck.ReleaseMutex(); return; } Thread th = null; bool status = false; StringBuilder sb = new StringBuilder(); try { sb.Append(e.Result); status = true; AllFailed = false; RenewNodeCount++; Logging.Debug(String.Format("mwcRunningCount {0} RenewNodeCount {1}", mwcRunningCount, RenewNodeCount)); th = new Thread(new ParameterizedThreadStart(thInvokeNewFeedNodeFound)); th.Start(new object[] { sb.ToString(), tmpmwc.task, status }); } catch (Exception ex) { if (ex.Message.Contains("cancel")) { mwcRunningCount--; RenewNodeCount--; Logging.Debug(String.Format("mwcRunningCount {0} RenewNodeCount {1}", mwcRunningCount, RenewNodeCount)); return; } #if DEBUG Logging.Debug(String.Format("Subscribe {0} on MyWebClient {1} {2}using proxy error in {3} s" + System.Environment.NewLine + "{4}", tmpmwc.task.index + 1, tmpmwc.mwcindex + 1, tmpmwc.task.DontUseProxy ? "not " : tmpmwc.task.UseProxy ? "" : use_proxy ? "" : "not ", (Program.sw.Elapsed.TotalMilliseconds - timerarray[tmpmwc.mwcindex]) / 1000.0, ex.Message.Contains("Check InnerException for exception details.") ? ex.InnerException.Message : ex.Message)); #endif if (!tmpmwc.task.DontUseProxy && !tmpmwc.task.UseProxy && config.nodeFeedAutoUpdateTryUseProxy && !use_proxy) { tmpmwc.task.UseProxy = true; mtListControl.WaitOne(); listServerSubscribes.Insert(0, tmpmwc.task); mtListControl.ReleaseMutex(); return; } if (listFailed != null) { listFailed.Add(tmpmwc.task.id); } RenewNodeCount++; Logging.Debug(String.Format("mwcRunningCount {0} RenewNodeCount {1}", mwcRunningCount, RenewNodeCount)); if (ex.Message.Contains("Check InnerException for exception details.") && ex.InnerException.Message == "The request was aborted: The request was canceled.") { Logging.Log(LogLevel.Info, String.Format(I18N.GetString("Update subscribe {0} timeout"), tmpmwc.task.index + 1)); } th = new Thread(new ParameterizedThreadStart(thInvokeNewFeedNodeFound)); th.Start(new object[] { sb.ToString(), tmpmwc.task, status }); } finally { #if DEBUG Logging.Debug(String.Format("Subscribe {0} on MyWebClient {1} {2}using proxy completed in {3} s", tmpmwc.task.index + 1, tmpmwc.mwcindex + 1, tmpmwc.task.DontUseProxy ? "not " : tmpmwc.task.UseProxy ? "" : use_proxy ? "" : "not ", (Program.sw.Elapsed.TotalMilliseconds - timerarray[tmpmwc.mwcindex]) / 1000.0)); timerarray[tmpmwc.mwcindex] = 0; #endif th = new Thread(new ParameterizedThreadStart(thStartDownloadString)); th.Start(new object[] { tmpmwc.mwcindex }); } }
private void Log_completedDownload(object sender, DownloadStringCompletedEventArgs args) { Utils.LogMe(args.Result, true); }
void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { if (e.Error != null) { DownloadHash(); return; } MD5 hash = new MD5CryptoServiceProvider(); String md5 = null, serverMD5 = null; var sb = new StringBuilder(); try { using (var fs = File.Open(_launcherFile, FileMode.Open, FileAccess.Read)) { var md5Bytes = hash.ComputeHash(fs); foreach (byte hex in md5Bytes) { sb.Append(hex.ToString("x2")); } md5 = sb.ToString().ToLowerInvariant(); fs.Seek(0, SeekOrigin.Begin); Byte[] magic = new Byte[2]; fs.Read(magic, 0, 2); if (magic[0] != 80 || magic[1] != 75) { throw new ApplicationException(); } } } catch (IOException ioException) { Console.WriteLine(ioException.Message); Console.WriteLine(ioException.StackTrace); MessageBox.Show("Cannot check launcher version, the launcher is currently open!", "Launcher Currently Open", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); Application.Exit(); return; } catch (ApplicationException appException) { MessageBox.Show("Unable to download launcher. Please check your internet connection by opening www.techniclauncher.net in your webbrowser.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); Application.Exit(); return; } catch (Exception exception) { Console.WriteLine(exception.Message); Console.WriteLine(exception.StackTrace); MessageBox.Show("Error checking launcher version", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); return; } var lines = e.Result.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None); foreach (var line in lines) { if (!line.Contains("technic-launcher.jar")) { continue; } serverMD5 = line.Split('|')[0].ToLowerInvariant(); break; } if (serverMD5 != null && serverMD5.Equals(md5)) { Program.RunLauncher(_launcherFile); Close(); } else { DownloadLauncher(); } }
private void WebClientDownloadCompleted(object sender, DownloadStringCompletedEventArgs e) { this.html = e.Result; this.DescargaFinalizada(this.html); }
/// <summary> /// Parse Vimeo API response to get video data (title, image, link). /// </summary> private void OnDownloadVimeoApiCompleted(object sender, DownloadStringCompletedEventArgs e) { try { if (!e.Cancelled) { if (e.Error == null) { var idx = e.Result.IndexOf("\"title\"", StringComparison.Ordinal); if (idx > -1) { idx = e.Result.IndexOf('"', idx + 7); if (idx > -1) { var endIdx = e.Result.IndexOf('"', idx + 1); while (e.Result[endIdx - 1] == '\\') { endIdx = e.Result.IndexOf('"', endIdx + 1); } if (endIdx > -1) { this._videoTitle = e.Result.Substring(idx + 1, endIdx - idx - 1).Replace("\\\"", "\""); } } } idx = e.Result.IndexOf("\"thumbnail_large\"", StringComparison.Ordinal); if (idx > -1) { if (string.IsNullOrEmpty(Width)) { Width = "640"; } if (string.IsNullOrEmpty(Height)) { Height = "360"; } } else { idx = e.Result.IndexOf("thumbnail_medium", idx); if (idx > -1) { if (string.IsNullOrEmpty(Width)) { Width = "200"; } if (string.IsNullOrEmpty(Height)) { Height = "150"; } } else { idx = e.Result.IndexOf("thumbnail_small", idx); if (string.IsNullOrEmpty(Width)) { Width = "100"; } if (string.IsNullOrEmpty(Height)) { Height = "75"; } } } if (idx > -1) { idx = e.Result.IndexOf("http:", idx); if (idx > -1) { var endIdx = e.Result.IndexOf('"', idx); if (endIdx > -1) { this._videoImageUrl = e.Result.Substring(idx, endIdx - idx).Replace("\\\"", "\"").Replace("\\", ""); } } } idx = e.Result.IndexOf("\"url\"", StringComparison.Ordinal); if (idx > -1) { idx = e.Result.IndexOf("http:", idx); if (idx > -1) { var endIdx = e.Result.IndexOf('"', idx); if (endIdx > -1) { this._videoLinkUrl = e.Result.Substring(idx, endIdx - idx).Replace("\\\"", "\"").Replace("\\", ""); } } } } else { HandleDataLoadFailure(e.Error, "Vimeo"); } } } catch (Exception ex) { HtmlContainer.ReportError(HtmlRenderErrorType.Iframe, "Failed to parse Vimeo video response", ex); } HandlePostApiCall(sender); }
private void OnCompleted_String(object sender, DownloadStringCompletedEventArgs e) { try { this.isNeedRetry = false; if (this.OnCompletedString != null) { if (e.Cancelled) { this.OnCompletedString(ERRORLEVEL.ERR_NEEDRETRY, "Download Cancelled"); } else if (e.Error != null) { this.ErrorString = e.Error.Message; if (e.Error.InnerException != null) { this.ErrorString = string.Format("{0} {1}", this.ErrorString, e.Error.InnerException.Message); if (e.Error.InnerException is SocketException) { this.OnCompletedString(ERRORLEVEL.ERR_NEEDRETRY, this.ErrorString); } else if (e.Error.InnerException is IOException) { if (e.Error.InnerException.InnerException != null) { if (e.Error.InnerException.InnerException is SocketException) { this.OnCompletedString(ERRORLEVEL.ERR_NEEDRETRY, this.ErrorString); } else { this.OnCompletedString(ERRORLEVEL.ERR_IOEXCEPTION, this.ErrorString); } } else { Logger.WriteLog(string.Format("Exception : {0}", e.Error.InnerException)); Logger.WriteLog(string.Format("Exception message : {0}", e.Error.InnerException.Message)); this.OnCompletedString(ERRORLEVEL.ERR_IOEXCEPTION, this.ErrorString); } } else { Logger.WriteLog(string.Format("Exception : {0}", e.Error.InnerException)); Logger.WriteLog(string.Format("Exception message : {0}", e.Error.InnerException.Message)); this.OnCompletedString(ERRORLEVEL.ERR_NETWORKEXCEPTION, this.ErrorString); } } else { Logger.WriteLog(string.Format("Exception : {0}", e.Error)); Logger.WriteLog(string.Format("Exception message : {0}", e.Error.InnerException.Message)); this.OnCompletedString(ERRORLEVEL.ERR_NETWORKEXCEPTION, this.ErrorString); } } else { string result = e.Result; this.OnCompletedString(ERRORLEVEL.SUCCESS, result); } } } catch (Exception ex) { Logger.WriteLog(string.Format("Exception : {0}", ex.Message)); this.OnCompletedString(ERRORLEVEL.ERR_NETWORKEXCEPTION, ex.Message); } }
/// <summary> /// Extends BeginInvoke so that when a state object is not needed, null does not need to be passed. /// <example> /// downloadstringcompletedeventhandler.BeginInvoke(sender, e, callback); /// </example> /// </summary> public static IAsyncResult BeginInvoke(this DownloadStringCompletedEventHandler downloadstringcompletedeventhandler, Object sender, DownloadStringCompletedEventArgs e, AsyncCallback callback) { if (downloadstringcompletedeventhandler == null) { throw new ArgumentNullException("downloadstringcompletedeventhandler"); } return(downloadstringcompletedeventhandler.BeginInvoke(sender, e, callback, null)); }
private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { //if (e.Error != null && _firstTry) //{ // _firstTry = false; // string url = "http://www.nikse.dk/Content/SubtitleEdit/Plugins/Plugins.xml"; // retry with alternate download url // var wc = new WebClient { Proxy = Utilities.GetProxy() }; // wc.Encoding = System.Text.Encoding.UTF8; // wc.Headers.Add("Accept-Encoding", ""); // wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted); // wc.DownloadStringAsync(new Uri(url)); // return; //} labelPleaseWait.Text = string.Empty; if (e.Error != null) { MessageBox.Show(string.Format(_language.UnableToDownloadPluginListX, e.Error.Message)); if (e.Error.InnerException != null) { MessageBox.Show(e.Error.InnerException.Source + ": " + e.Error.InnerException.Message + Environment.NewLine + Environment.NewLine + e.Error.InnerException.StackTrace); } return; } _updateAllListUrls = new List <string>(); _updateAllListNames = new List <string>(); try { _pluginDoc.LoadXml(e.Result); string[] arr = _pluginDoc.DocumentElement.SelectSingleNode("SubtitleEditVersion").InnerText.Split(new[] { '.', ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); double requiredVersion = Convert.ToDouble(arr[0] + "." + arr[1], CultureInfo.InvariantCulture); string[] versionInfo = Utilities.AssemblyVersion.Split('.'); double currentVersion = Convert.ToDouble(versionInfo[0] + "." + versionInfo[1], CultureInfo.InvariantCulture); if (currentVersion < requiredVersion) { MessageBox.Show(_language.NewVersionOfSubtitleEditRequired); DialogResult = DialogResult.Cancel; return; } foreach (XmlNode node in _pluginDoc.DocumentElement.SelectNodes("Plugin")) { ListViewItem item = new ListViewItem(node.SelectSingleNode("Name").InnerText.Trim('.')); item.SubItems.Add(node.SelectSingleNode("Description").InnerText); item.SubItems.Add(node.SelectSingleNode("Version").InnerText); item.SubItems.Add(node.SelectSingleNode("Date").InnerText); listViewGetPlugins.Items.Add(item); foreach (ListViewItem installed in listViewInstalledPlugins.Items) { if (installed.Text.TrimEnd('.') == node.SelectSingleNode("Name").InnerText.TrimEnd('.') && installed.SubItems[2].Text.Replace(",", ".") != node.SelectSingleNode("Version").InnerText.Replace(",", ".")) { //item.BackColor = Color.LightGreen; installed.BackColor = Color.LightPink; installed.SubItems[1].Text = _language.UpdateAvailable + " " + installed.SubItems[1].Text; buttonUpdateAll.Visible = true; _updateAllListUrls.Add(node.SelectSingleNode("Url").InnerText); _updateAllListNames.Add(node.SelectSingleNode("Name").InnerText); } } } } catch (Exception exception) { MessageBox.Show(string.Format(_language.UnableToDownloadPluginListX, exception.Source + ": " + exception.Message + Environment.NewLine + Environment.NewLine + exception.StackTrace)); } if (_updateAllListUrls.Count > 0) { buttonUpdateAll.BackColor = Color.LightGreen; if (Configuration.Settings.Language.PluginsGet.UpdateAllX != null) { buttonUpdateAll.Text = string.Format(Configuration.Settings.Language.PluginsGet.UpdateAllX, _updateAllListUrls.Count); } else { buttonUpdateAll.Text = Configuration.Settings.Language.PluginsGet.UpdateAll; } buttonUpdateAll.Visible = true; } }
private void downloadJsonCompleted(object sender, DownloadStringCompletedEventArgs e) { try { if (e.Error == null && !e.Cancelled) { string data = e.Result; JObject obj = JObject.Parse(data); movie.summary = JsonParsers.getValue(obj, "summary"); if (movie.genre == "" || movie.genre == null) { movie.genre = JsonParsers.getArray(obj, "genres"); } if (movie.title == "" || movie.title == null) { movie.title = JsonParsers.getValue(obj, "title"); } if (movie.year == "" || movie.year == null) { movie.year = JsonParsers.getValue(obj, "year"); } if (movie.rating == "" || movie.rating == null) { movie.rating = JsonParsers.getDouble(obj, "rating", "average"); } movie.star = Util.getStarPath(movie.rating); if (movie.rateNumber == "" || movie.rateNumber == null) { movie.rateNumber = JsonParsers.getValue(obj, "ratings_count"); } if (movie.posterUrl == "" || movie.posterUrl == null) { movie.posterUrl = JsonParsers.getDouble(obj, "images", "small"); } object[] countries = obj["countries"].ToArray(); if (movie.region == "" || movie.region == null) { movie.region = JsonParsers.getArray(obj, "countries"); } if (movie.posterUrl == "") { movie.posterUrl = App.imagePath + "default.png"; } setUI(); List <People> peoples = new List <People>(); JArray array = (JArray)obj["directors"]; for (int i = 0; i < array.Count; i++) { People people = new People(); people.posterUrl = JsonParsers.getDouble(array[i], "avatars", "small"); if (people.posterUrl == "") { people.posterUrl = App.imagePath + "default.png"; } people.id = JsonParsers.getValue(array[i], "id"); people.name = JsonParsers.getValue(array[i], "name"); people.positionName = "导演"; people.position = People.DIRECTOR; peoples.Add(people); } array = (JArray)obj["casts"]; for (int i = 0; i < array.Count; i++) { People people = new People(); people.posterUrl = JsonParsers.getDouble(array[i], "avatars", "small"); if (people.posterUrl == "") { people.posterUrl = App.imagePath + "default.png"; } people.id = JsonParsers.getValue(array[i], "id"); people.name = JsonParsers.getValue(array[i], "name"); people.positionName = ""; people.position = People.ACTOR; peoples.Add(people); } movie.peopleList = peoples; peopleList.ItemsSource = peoples; // Insert movie into cache Cache.insertMovie(movie); if (progressBar != null) { progressBar.Visibility = Visibility.Collapsed; } } else { var wEx = e.Error as WebException; if (wEx.Status == WebExceptionStatus.RequestCanceled) { if (App.isFromDormant) { App.isFromDormant = false; getMovieByID(); } } if (progressBar != null) { progressBar.Visibility = Visibility.Collapsed; } } } catch (WebException) { if (progressBar != null) { progressBar.Visibility = Visibility.Collapsed; } MessageBoxResult result = MessageBox.Show(AppResources.ConnectionError, "", MessageBoxButton.OK); } catch (Exception) { if (progressBar != null) { progressBar.Visibility = Visibility.Collapsed; } } }
void _CommandClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { }
void statusRequestCompleted(object sender, DownloadStringCompletedEventArgs e) { // If playback just finished, or if there was some type of error, skip it if (!_MonitorPlayback || e.Cancelled || e.Error != null || string.IsNullOrEmpty(e.Result) || (DateTime.Now - _lastReport).Ticks < ReportInterval) { return; } _lastReport = DateTime.Now; _ConsecutiveFailedHttpRequests = 0; string result = e.Result; Logger.ReportVerbose("Response received from MPC-HC web interface: " + result); try { // Sample result // OnStatus('test.avi', 'Playing', 5292, '00:00:05', 1203090, '00:20:03', 0, 100, 'C:\test.avi') // 5292 = position in ms // 00:00:05 = position // 1203090 = duration in ms // 00:20:03 = duration char quoteChar = result.IndexOf(", \"") == -1 ? '\'' : '\"'; // Strip off the leading "OnStatus(" and the trailing ")" result = result.Substring(result.IndexOf(quoteChar)); result = result.Substring(0, result.LastIndexOf(quoteChar)); // Strip off the filename at the beginning result = result.Substring(result.IndexOf(string.Format("{0}, {0}", quoteChar)) + 3); // Find the last index of ", '" so that we can extract and then strip off the file path at the end. int lastIndexOfSeparator = result.LastIndexOf(", " + quoteChar); // Get the current playing file path string currentPlayingFile = result.Substring(lastIndexOfSeparator + 2).Trim(quoteChar); // Strip off the current playing file path result = result.Substring(0, lastIndexOfSeparator); IEnumerable <string> values = result.Split(',').Select(v => v.Trim().Trim(quoteChar)); long currentPositionTicks = TimeSpan.FromMilliseconds(double.Parse(values.ElementAt(1))).Ticks; long currentDurationTicks = TimeSpan.FromMilliseconds(double.Parse(values.ElementAt(3))).Ticks; string playstate = values.ElementAt(0).ToLower(); Logger.ReportVerbose("File: {0} Position {1} Status {2}", currentPlayingFile, currentPositionTicks, playstate); _CurrentPlayState = playstate; if (playstate == "stopped") { if (_HasStartedPlaying) { ClosePlayer(); } } else { if (playstate == "playing") { _HasStartedPlaying = true; } if (_HasStartedPlaying) { OnProgress(GetPlaybackState(currentPositionTicks, currentDurationTicks)); } } } catch (Exception ex) { Logger.ReportException("Unrecognized response in MPC-HC web interface.", ex); } }
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { lblActTask.Text = "Prüfe auf neue Version..."; UpdateConfig = UpdateConfig.Deserialize(e.Result); DownloadFiles(); }
void RefreshCompleted(object sender, DownloadStringCompletedEventArgs e) { if (!e.Cancelled && e.Error == null) { _update = JsonConvert.DeserializeObject<JSONUpdate>(e.Result); if (_update.VersionCode > VersionCode || _update.Force) { richTextBox1.Text += dot + "A new update is available (version " + _update.Version + "). Changelog:\n"; if (!_update.Manual) { richTextBox1.Text += _update.Changelog + "\n\n" + dot + "Press \"Download update\" to begin.\n"; button_download.Enabled = true; } else { richTextBox1.Text += _update.Changelog + "\n\n" + dot + "Automatic update not possible. Please visit the Icy Monitor website to download the update.\n"; } } else { richTextBox1.Text += dot + "No new updates available.\n"; } } else { richTextBox1.Text += dot + "Could not contact update server.\n"; } }
// start parsing image file url after containing html page downloaded void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { string htmlPage = e.Result; System.Diagnostics.Debug.WriteLine("---------html---------"+sender.ToString()); System.Diagnostics.Debug.WriteLine(htmlPage); int startIndex = htmlPage.IndexOf("<title>"); int endIndex = htmlPage.IndexOf("</title>"); string titleText = htmlPage.Substring(startIndex + 7, endIndex - startIndex - 7); //string imgUrlPattern = "<img\\ssrc[^>]*jpg\">"; string imgUrlPattern = "http:[^>]*jpg"; MatchCollection matches = Regex.Matches(htmlPage, imgUrlPattern, RegexOptions.IgnoreCase); foreach (Match m in matches) { System.Diagnostics.Debug.WriteLine(m.ToString()); try { Uri imgUri = new Uri(m.ToString()); imgUriList.Add(imgUri); dict.Add(imgUri, titleText); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); continue; } } System.Diagnostics.Debug.WriteLine("\n---------hiee---------"+matches.Count); //throw new NotImplementedException(); topicPageCount -= 1; if (topicPageCount == 0) BeginDownloadImage(imgUriList.ElementAt(0)); }