/// <summary> /// Loads a bitmap from the web or a file and displays. /// </summary> public void LoadImage( string url ) { if(url != null && !url.ToLower().StartsWith("http://")) { // Local file Image = Image.FromFile(url); return; } oldText = Text; Text = Text + ": Loading..."; using(WebDownload client = new WebDownload(url)) { client.DownloadMemory(); DownloadComplete(client); } }
/// <summary> /// Returns an array of satellite Tles from the input URL /// </summary> /// <param name="url"></param> /// <returns></returns> public ArrayList GetFromWeb(string url ) { string line1=null,line2=null; bool useLocalFile = false; ArrayList satTles = new ArrayList(); string saveto =Path.Combine( this.Plugin.PluginDirectory,this.Name +".txt"); //Get the TLE data using( WebDownload dl = new WebDownload(url) ) { try { dl.DownloadMemory(); dl.SaveMemoryDownloadToFile(saveto); } catch(System.Net.WebException) { useLocalFile = true; } if(useLocalFile) using(TextReader tr = new StreamReader( saveto )) { string[] line = tr.ReadToEnd().Split('\n'); string NumFormat = GetNumberFormat(line); for(int i=0;i<line.Length-1-2;i = i + 3) { if(line[i].Trim().Length == 0) break; line1 = line[i+1].Trim(); line2 = line[i+2].Trim(); Tle tle = new Tle(FormatTrailingNumber(line[i].Trim(), NumFormat), line1, line2); satTles.Add(tle); } } else using(TextReader tr = new StreamReader( dl.ContentStream )) { string[] line = tr.ReadToEnd().Split('\n'); string NumFormat = GetNumberFormat(line); for(int i=0;i<line.Length-1-2;i = i + 3) { if(line[i].Trim().Length == 0) break; line1 = line[i+1].Trim(); line2 = line[i+2].Trim(); Tle tle = new Tle(FormatTrailingNumber(line[i].Trim(), NumFormat), line1, line2); satTles.Add(tle); } } } return satTles; }
public void DownloadData(string SEARCHMETHOD1_Text, string SYEAR_Text, string SMONTH_Text, string SDAY_Text, string EYEAR_Text, string EMONTH_Text, string EDAY_Text, string LMAG_Text, string UMAG_Text, string NDEP1_Text, string NDEP2_Text, string SLAT2_Text, string SLAT1_Text, string SLON2_Text, string SLON1_Text, string CLAT_Text, string CLON_Text, string CRAD_Text) { // Download the queried data string USGSUrl = "http://eqint.cr.usgs.gov/neic/cgi-bin/epic/epic.cgi?SEARCHMETHOD=" + SEARCHMETHOD1_Text + "&FILEFORMAT=6&SEARCHRANGE=HH&SYEAR=" + SYEAR_Text + "&SMONTH=" + SMONTH_Text + "&SDAY=" + SDAY_Text + "&EYEAR=" + EYEAR_Text + "&EMONTH=" + EMONTH_Text + "&EDAY=" + EDAY_Text + "&LMAG=" + LMAG_Text + "&UMAG=" + UMAG_Text + "&NDEP1=" + NDEP1_Text + "&NDEP2=" + NDEP2_Text + "&IO1=&IO2=&SLAT2=" + SLAT2_Text + "&SLAT1=" + SLAT1_Text + "&SLON2=" + SLON2_Text + "&SLON1=" + SLON1_Text + "&CLAT=" + CLAT_Text + "&CLON=" + CLON_Text + "&CRAD=" + CRAD_Text + "&SUBMIT=Submit+Search"; //MessageBox.Show("Submited URL: "+USGSUrl); ClearIcons(); owner.EQIcons.IsOn = true; WebDownload dl = new WebDownload(USGSUrl); dl.DownloadMemory(WorldWind.Net.DownloadType.Unspecified); CultureInfo icy = CultureInfo.InvariantCulture; // Create a reader to read the response from the server StreamReader reader = new StreamReader(dl.ContentStream); string line; // Find the 1/3 break point for the date range DateTime CStartDate = new DateTime(int.Parse(SYEAR_Text, icy), int.Parse(SMONTH_Text, icy), int.Parse(SDAY_Text, icy)); DateTime CEndDate = new DateTime(int.Parse(EYEAR_Text, icy), int.Parse(EMONTH_Text, icy), int.Parse(EDAY_Text, icy)); TimeSpan diff = TimeSpan.FromDays((CEndDate - CStartDate).TotalDays / 3); // Counting Earthquakes int QuakeCount = 0; int CountSmall = 0; int CountMedium = 0; int CountLarge = 0; int CountMajor = 0; ArrayList quakeList = new ArrayList(); while ((line = reader.ReadLine()) != null) { string[] fields = line.Trim().Split(','); if ((fields.Length < 8) || (fields.Length > 0 && fields[0] == "Year")) continue; // The rest is for displaying the earthquake markers string Q_Date = fields[1] + "/" + fields[2] + "/" + fields[0];// Pulls out the date of the Earthquake string Q_Time = fields[3];// Get the Earthquake even time float Latitude = float.Parse(fields[4], icy);// Get the Latitude float Longitude = float.Parse(fields[5], icy);// Get the Longitude float Magnitude = 0; if (fields[6].Trim().Length > 0) Magnitude = float.Parse(fields[6], icy);// Get the Magnitude float Depth = float.Parse(fields[7], icy);// Get the Depth of the Earthquake DateTime DateCompare = new DateTime(int.Parse(fields[0], icy), int.Parse(fields[1], icy), int.Parse(fields[2], icy)); QuakeItem curQuakeItem = new QuakeItem(); curQuakeItem.Depth = Depth; curQuakeItem.Latitude = Latitude; curQuakeItem.Longitude = Longitude; curQuakeItem.Magnitude = Magnitude; curQuakeItem.Q_Date = Q_Date; curQuakeItem.Q_Time = Q_Time; curQuakeItem.DateCompare = DateCompare; quakeList.Add(curQuakeItem); int IconWidth = 20; int IconHeight = 20; string bitmapShape = "circle"; string bitmapColor = "red"; if (DateCompare < (CStartDate + diff)) bitmapColor = "green"; else if (DateCompare > (CEndDate - diff)) bitmapColor = "red"; else bitmapColor = "yellow"; if (Depth <= 40) // Shallow Depth { bitmapShape = "circle"; } else if ((Depth == 41) || (Depth <= 70)) // Medium Depth { bitmapShape = "triangle"; } else if ((Depth == 71) || (Depth <= 200)) // Deep Depth { bitmapShape = "square"; } else // Ultra Deep { bitmapShape = "star"; } if (Magnitude <= 3.5) // Small Icons { CountSmall = CountSmall + 1; IconWidth = 20; IconHeight = 20; } else if ((Magnitude == 3.6) || (Magnitude <= 5.5)) // Medium Icons { CountMedium = CountMedium + 1; IconWidth = 33; IconHeight = 33; } else if ((Magnitude == 5.6) || (Magnitude <= 7.0)) // Large Icons { CountLarge = CountLarge + 1; IconWidth = 48; IconHeight = 48; } else // Major Icons { CountMajor = CountMajor + 1; IconWidth = 60; IconHeight = 60; } string bitmapFileName = String.Format("{0}_{1}.png", bitmapShape, bitmapColor); string bitmapFullPath = Path.Combine(owner.PluginDirectory, bitmapFileName); // Increase the count QuakeCount = QuakeCount + 1; // Disply the icon and related data WorldWind.Renderable.Icon ic = new WorldWind.Renderable.Icon( Q_Date + " - " + Magnitude, // name Latitude, Longitude, 0); // DistanceAboveSurface ic.Description = "Earthquake Details: \n Date: " + Q_Date + "\n Time: " + Q_Time + " UTC\n Magnitude: " + Magnitude + "\n Depth: " + Depth + " Km"; // description ic.TextureFileName = bitmapFullPath; // textureFullPath ic.Width = IconWidth; // IconWidthPixels ic.Height = IconHeight; //IconHeightPixels ic.ClickableActionURL = ""; //ClickableUrl // Add the icon to the layer owner.EQIcons.AddIcon(ic); } // show count //MessageBox.Show("Number of Earthquakes Found: "+ QuakeCount); this.QuakesFoundNumber.Text = QuakeCount.ToString(); this.MajorQuakeNumber.Text = CountMajor.ToString(); this.LargeQuakeNumber.Text = CountLarge.ToString(); this.MediumQuakeNumber.Text = CountMedium.ToString(); this.SmallQuakeNumber.Text = CountSmall.ToString(); //check the top five quakes quakesMagSortList.Clear(); foreach (QuakeItem curQuakeItem in quakeList) { bool quakeAdded = false; for (int i = 0; i < quakesMagSortList.Count; i++) { QuakeItem quakeItem = (QuakeItem)quakesMagSortList[i]; if (curQuakeItem.Magnitude >= quakeItem.Magnitude) { quakesMagSortList.Insert(i, curQuakeItem); quakeAdded = true; break; } } if (!quakeAdded) { quakesMagSortList.Add(curQuakeItem); } } int numberTopQuakes = 5; if (quakesMagSortList.Count < numberTopQuakes) numberTopQuakes = quakesMagSortList.Count; for (int i = 0; i < numberTopQuakes; i++) { QuakeItem quakeItem = (QuakeItem)quakesMagSortList[i]; switch (i) { case 0: TQlink1.BeginInvoke(new SetControlTextDelegate(SetControlText), new object[] { TQlink1, string.Format("{0} - {1}", quakeItem.Q_Date, quakeItem.Magnitude) }); break; case 1: TQlink2.BeginInvoke(new SetControlTextDelegate(SetControlText), new object[] { TQlink2, string.Format("{0} - {1}", quakeItem.Q_Date, quakeItem.Magnitude) }); break; case 2: TQlink3.BeginInvoke(new SetControlTextDelegate(SetControlText), new object[] { TQlink3, string.Format("{0} - {1}", quakeItem.Q_Date, quakeItem.Magnitude) }); break; case 3: TQlink4.BeginInvoke(new SetControlTextDelegate(SetControlText), new object[] { TQlink4, string.Format("{0} - {1}", quakeItem.Q_Date, quakeItem.Magnitude) }); break; case 4: TQlink5.BeginInvoke(new SetControlTextDelegate(SetControlText), new object[] { TQlink5, string.Format("{0} - {1}", quakeItem.Q_Date, quakeItem.Magnitude) }); break; } } if (numberTopQuakes < 5) { if (numberTopQuakes == 4) TQlink4.Text = ""; if (numberTopQuakes < 4) TQlink3.Text = ""; if (numberTopQuakes < 3) TQlink2.Text = ""; if (numberTopQuakes < 1) TQlink1.Text = ""; } }
/// <summary> /// Loads table of contents from server and populates the list box. /// PS: Not running in UI thread (Invoke when updating UI) /// </summary> private void RefreshCapabilitiesFromUrl() { try { // Read capabilities from server updateStatusBar("Downloading updated table of contents..."); string wmsQueryString = AnimatedEarthManager.ServerUrl + "?service=" + this.serviceName + "&version=" + WmsVersion + "&request=GetCapabilities"; using( WebDownload download = new WebDownload(wmsQueryString) ) { download.ProgressCallback += new DownloadProgressHandler( this.updateCurrentProgressBar ); download.DownloadMemory(); try { // Save the downloaded capabilities for future (off-line) use download.SaveMemoryDownloadToFile(CapabilitiesFilePath); } catch(Exception) { //For read-only cache support etc. // UnauthorizedException, IOException etc. } RefreshCapabilities( download.ContentStream ); } isRefreshed = true; } catch { updateStatusBar("Connection Error. Please try again later."); } this.updateCurrentProgressBar(0,0); }
/// <summary> /// Downloads image from web /// </summary> protected void DownloadImage() { try { if(_imagePath!=null) Directory.CreateDirectory(Path.GetDirectoryName(this._imagePath)); using(WebDownload downloadReq = new WebDownload(this._imageUrl)) { downloadReq.ProgressCallback += new DownloadProgressHandler(UpdateDownloadProgress); string filePath = getFilePathFromUrl(_imageUrl); if(_imagePath==null) { // Download to RAM downloadReq.DownloadMemory(); texture = ImageHelper.LoadTexture(downloadReq.ContentStream); } else { downloadReq.DownloadFile(_imagePath); UpdateTexture(_imagePath); } CreateMesh(); isInitialized = true; } } catch(ThreadAbortException) {} catch(Exception caught) { if(!showedError) { string msg = string.Format("Image download of file\n\n{1}\n\nfor layer '{0}' failed:\n\n{2}", name, _imageUrl, caught.Message ); System.Windows.Forms.MessageBox.Show(msg, "Image download failed.", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error ); showedError = true; } if(_imagePath != null) { FileInfo imageFile = new FileInfo(_imagePath); if(imageFile.Exists) { UpdateTexture(_imagePath); CreateMesh(); isInitialized = true; } } else { isOn = false; } } }
public void DownloadImage() { try { this.downloadState = DownloadState.Downloading; this.downloadProgress = 0.0f; if(File.Exists(this.saveTexturePath)) File.Delete(this.saveTexturePath); if(!Directory.Exists(Path.GetDirectoryName(this.saveTexturePath))) Directory.CreateDirectory(Path.GetDirectoryName(this.saveTexturePath)); using( WebDownload dl = new WebDownload(imageUrl)) { dl.ProgressCallback += new DownloadProgressHandler(UpdateProgress); dl.DownloadMemory(); this.downloadState = DownloadState.Converting; ImageHelper.ConvertToDxt1(dl.ContentStream, saveTexturePath); } if(this.downloadState == DownloadState.Cancelled) return; this.IsTextureAvailable = true; if(this.LoadImage) { this.imageLayer = new ImageLayer(this.Name, m_ParentWorld, this.layerRadius - (float)m_ParentWorld.EquatorialRadius, this.saveTexturePath, this.south, this.north, this.west, this.east, 255, /*this.terrainInfo*/null); } this.downloadState = DownloadState.Pending; } catch(Exception caught) { Log.Write( caught ); } }
/// <summary> /// Search WWC's placename db /// </summary> private void SearchOnline() { // Stop unnecessary queryies if (this.textBoxWWFeature.Text == lastSearchTerm || this.textBoxWWFeature.Text == "Keyword(s)") { return; } this.listViewResults.Items.Clear(); this.listViewResults.Columns.Clear(); this.listViewResults.Columns.Add("Name", 150, HorizontalAlignment.Left); this.listViewResults.Columns.Add("Country", 120, HorizontalAlignment.Left); this.listViewResults.Columns.Add("Region", 80, HorizontalAlignment.Left); this.listViewResults.Columns.Add("Type", 90, HorizontalAlignment.Left); this.listViewResults.Columns.Add("Latitude", 60, HorizontalAlignment.Left); this.listViewResults.Columns.Add("Longitude", 60, HorizontalAlignment.Left); this.statusBar.BeginInvoke(new SetStatusMessageDelegate(SetStatusMessage), new object[] { "Searching global placenames..." }); XmlTextReader reader = null; try { string query = this.textBoxWWFeature.Text; // use '+' for an AND query if (query.Contains(" ")) { query = "+" + query; query = Regex.Replace(query, @"\s+", " +"); } //urlencode query string string urlQuery = HttpUtility.UrlEncode(query); string searchUriString = "http://s0.tileservice.worldwindcentral.org/queryGeoNames?q=" + urlQuery + "&columns=className,countryName,priAdmName,latitude,longitude,name,origName"; try { WorldWind.Net.WebDownload dl = new WorldWind.Net.WebDownload(searchUriString); dl.Compressed = true; dl.DownloadMemory(); if (String.Compare("gzip", dl.ContentEncoding, true) == 0) { GZipStream uncompressed = new GZipStream(dl.ContentStream, CompressionMode.Decompress); reader = new XmlTextReader(uncompressed); } else { reader = new XmlTextReader(dl.ContentStream); } // Stop duplicate searches lastSearchTerm = this.textBoxWWFeature.Text; } catch (Exception ex) { MessageBox.Show(ex.Message); } int counter = 0; while (reader.Read()) { if (reader.Name == "Row") { string name = null; if (reader.GetAttribute("origName") == "") { name = reader.GetAttribute("name"); } else { name = reader.GetAttribute("origName"); } //string name = reader.GetAttribute("name"); string sLon = reader.GetAttribute("longitude"); string sLat = reader.GetAttribute("latitude"); string country = reader.GetAttribute("countryName"); string region = reader.GetAttribute("priAdmName"); string type = reader.GetAttribute("className"); double lon = double.Parse(sLon, CultureInfo.InvariantCulture); double lat = double.Parse(sLat, CultureInfo.InvariantCulture); ListViewItem item = new ListViewItem(new string[] { name, country, region, type, lat.ToString(CultureInfo.CurrentCulture), lon.ToString(CultureInfo.CurrentCulture) }); listViewResults.Items.Add(item); counter++; } } if (counter != 0) { string status = "Found " + counter + " results from global placenames."; this.statusBar.BeginInvoke(new SetStatusMessageDelegate(SetStatusMessage), new object[] { status }); } else { this.statusBar.BeginInvoke(new SetStatusMessageDelegate(SetStatusMessage), new object[] { "Found no results." }); } } catch (XmlException xmle) { MessageBox.Show(xmle.Message); } }
private void SearchFunction() { try { if(m_CurrentSearchUri != null) { //using(WebClient client = new WebClient()) using(WebDownload client = new WebDownload(m_CurrentSearchUri)) { client.DownloadMemory(); XmlTextReader reader = new XmlTextReader(client.ContentStream); ArrayList resultList = new ArrayList(); Hashtable curResult = new Hashtable(); while(reader.Read()) { if(reader.NodeType == XmlNodeType.Element) { if(reader.Name != "Result" && reader.Name != "ResultSet") { //results come from Yahoo with . a the decimal separator, //but are parsed so they appear in the list using the local //settings if (reader.Name == "Latitude" || reader.Name == "Longitude") { string sval = reader.ReadString(); double dval = double.Parse(sval, CultureInfo.InvariantCulture); curResult.Add(reader.Name, dval.ToString()); } else curResult.Add(reader.Name, reader.ReadString()); } } else if(reader.NodeType == XmlNodeType.EndElement) { if(reader.Name.Equals("Result")) { resultList.Add(curResult); curResult = new Hashtable(); } } } foreach(Hashtable r in resultList) { string[] parts = new string[this.listViewResults.Columns.Count]; for(int i = 0; i < this.listViewResults.Columns.Count; i++) { parts[i] = (string)r[this.listViewResults.Columns[i].Text]; } this.listViewResults.Items.Add(new ListViewItem(parts)); } } } this.statusBar.BeginInvoke(new SetStatusMessageDelegate(SetStatusMessage), new object[] {this.listViewResults.Items.Count.ToString() + " Yahoo results found"}); } catch { this.statusBar.BeginInvoke(new SetStatusMessageDelegate(SetStatusMessage), new object[] { "Error searching Yahoo" }); } }
private void Downloader() { WMSDownload wmsDownload = null; while(true) { try { lock(this.downloadQueue) { if(this.downloadQueue.Count <= 0) // Queue empty return; wmsDownload = (WMSDownload)this.downloadQueue.Dequeue(); } if(this.checkBoxAnimationCache.Checked && File.Exists(wmsDownload.SavedFilePath + ".wwi") && File.Exists(wmsDownload.SavedFilePath + ".dds")) { try { ImageLayerInfo imageLayerInfo = ImageLayerInfo.FromFile(wmsDownload.SavedFilePath + ".wwi"); const float epsilon = Single.Epsilon*100; if(Math.Abs(imageLayerInfo.North - (float)wmsDownload.North)<epsilon && Math.Abs(imageLayerInfo.South - (float)wmsDownload.South)<epsilon && Math.Abs(imageLayerInfo.West - (float)wmsDownload.West)<epsilon && Math.Abs(imageLayerInfo.East - (float)wmsDownload.East)<epsilon) { lock(this.animationFrames.SyncRoot) { animationFrames.Add(imageLayerInfo); // Process next queue item continue; } } } // Cached file not readable for some reason - reload catch(IOException) {} catch(FormatException) {} } UpdateStatusBar( "Downloading: " + Path.GetFileName(wmsDownload.SavedFilePath) ); using( WebDownload dl = new WebDownload(wmsDownload.Url) ) { dl.ProgressCallback += new DownloadProgressHandler(this.updateCurrentProgressBar); dl.DownloadMemory(DownloadType.Wms); if(this.animationState == AnimationState.Cancel || this.animationState == AnimationState.Stop) return; dl.Verify(); ProcessDownloadedImage(wmsDownload, dl.ContentStream); } } catch(WebException caught) { this.worldWindow.Caption = caught.Message; } finally { updateCurrentProgressBar(0,1); } } }
internal void downloadThumbnail() { if (!MainForm.Settings.UseDappleSearch) return; WebDownload oThumbnailDownload = new WebDownload(MainForm.Settings.DappleSearchURL + "Thumbnail.aspx?layerid=" + m_aCommonAttributes["obaselayerid"], false); try { oThumbnailDownload.DownloadMemory(); m_oBitmap = new Bitmap(oThumbnailDownload.ContentStream); } catch (Exception) { m_oBitmap = Dapple.Properties.Resources.delete; } }
/// <summary> /// Retrieves a bitmap from cache or the web /// </summary> /// <param name="filename">The URI to download the bitmap from</param> /// <returns>The downloaded bitmap</returns> private string GetWebImage(string filename) { // Try using a cached version if (bitmapCache.ContainsKey(filename)) return filename; // Download the file from the web WebDownload myDownload = new WebDownload(filename); myDownload.DownloadMemory(); // Load it into a Bitmap Bitmap bit = (Bitmap)System.Drawing.Bitmap.FromStream(myDownload.ContentStream); // Cache the downloaded bitmap myDownload.Dispose(); bitmapCache.Add(filename, bit); return filename; }