Beispiel #1
0
		void DownloadComplete( WebDownload downloadInfo )
		{
			if(this.InvokeRequired)
			{
				Invoke(new DownloadCompleteHandler(DownloadComplete), new object[]{downloadInfo});
				return;
			}

			try
			{
				downloadInfo.Verify();
				Image = System.Drawing.Image.FromStream(downloadInfo.ContentStream);
			}
			catch(Exception caught)
			{
				this.Visible = false;
				MessageBox.Show(caught.Message, "Legend image download failed.",
					MessageBoxButtons.OK,MessageBoxIcon.Warning);
			}
			finally
			{
				if(downloadInfo!=null)
					downloadInfo.Dispose();
				Text = oldText;
			}
		}
Beispiel #2
0
        public void UpdateTexture(Device device, string textureFileName)
        {
            if ((textureFileName != null) && textureFileName.Length > 0)
            {
                if (textureFileName.ToLower().StartsWith("http://") && BaseSavePath != null)
                {
                    // download it
                    try
                    {
                        Uri uri = new Uri(textureFileName);

                        // Set the subdirectory path to the hostname and replace . with _
                        string savePath = uri.Host;
                        savePath = savePath.Replace('.', '_');

                        // build the save file name from the component pieces
                        savePath = BaseSavePath + @"\" + savePath + uri.AbsolutePath;
                        savePath = savePath.Replace('/', '\\');

                        // Offline check
                        if (!World.Settings.WorkOffline)
                        {
                            Net.WebDownload webDownload = new Net.WebDownload(textureFileName);
                            webDownload.DownloadType = Net.DownloadType.Unspecified;
                            webDownload.DownloadFile(savePath);
                        }

                        // reset the texture file name for later use.
                        textureFileName = savePath;
                    }
                    catch { }
                }
            }

            // Clear old texture - don't know if this is necessary so commented out for the moment
            //if (Texture != null)
            //{
            //    Texture.Dispose();
            //}

            if (ImageHelper.IsGdiSupportedImageFormat(textureFileName))
            {
                // Load without rescaling source bitmap
                using (Image image = ImageHelper.LoadImage(textureFileName)) this.LoadImage(device, image);
            }
            else
            {
                // Only DirectX can read this file, might get upscaled depending on input dimensions.
                this.Texture = ImageHelper.LoadIconTexture(textureFileName);
                // Read texture level 0 size
                using (Surface s = this.Texture.GetSurfaceLevel(0))
                {
                    SurfaceDescription desc = s.Description;
                    this.Width  = desc.Width;
                    this.Height = desc.Height;
                }
            }
        }
		private void DownloadComplete(WebDownload downloadInfo)
		{
            Log.Write(Log.Levels.Debug+1, "GSDR", "Download completed for " + downloadInfo.Url);
            try
			{
				downloadInfo.Verify();

				m_quadTile.QuadTileSet.NumberRetries = 0;

				// Rename temp file to real name
				File.Delete(m_localFilePath);
				File.Move(downloadInfo.SavedFilePath, m_localFilePath);

				// Make the quad tile reload the new image
				m_quadTile.DownloadRequest = null;
				m_quadTile.Initialize();
			}
			catch(System.Net.WebException caught)
			{
				System.Net.HttpWebResponse response = caught.Response as System.Net.HttpWebResponse;
				if(response!=null && response.StatusCode==System.Net.HttpStatusCode.NotFound)
				{
					using(File.Create(m_localFilePath + ".txt"))
					{}
					return;
				}
				m_quadTile.QuadTileSet.NumberRetries++;
			}
			catch
			{
				using(File.Create(m_localFilePath + ".txt"))
				{}
                if (File.Exists(downloadInfo.SavedFilePath))
                {
                    try
                    {
                        File.Delete(downloadInfo.SavedFilePath);
                    }
                    catch (Exception e)
                    {
                        Log.Write(Log.Levels.Error, "GSDR", "could not delete file " + downloadInfo.SavedFilePath + ":");
                        Log.Write(e);
                    }
                }
			}
			finally
			{
                if(download != null)
    				download.IsComplete = true;
				m_quadTile.QuadTileSet.RemoveFromDownloadQueue(this);

                // potential deadlock! -step
                // Immediately queue next download
                m_quadTile.QuadTileSet.ServiceDownloadQueue();
			}
		}
Beispiel #4
0
        public override void Initialize(DrawArgs drawArgs)
        {
            if (this.m_points == null)
            {
                this.isInitialized = true;
                return;
            }

            if (this.m_imageUri != null)
            {
                //load image
                if (this.m_imageUri.ToLower().StartsWith("http://"))
                {
                    string             savePath = string.Format("{0}\\image", ConfigurationLoader.GetRenderablePathString(this));
                    System.IO.FileInfo file     = new System.IO.FileInfo(savePath);

                    if (!file.Exists)
                    {
                        //Offline check
                        if (!World.Settings.WorkOffline)
                        {
                            Net.WebDownload download = new Net.WebDownload(this.m_imageUri);

                            if (!file.Directory.Exists)
                            {
                                file.Directory.Create();
                            }

                            download.DownloadFile(file.FullName, Net.DownloadType.Unspecified);
                        }
                    }

                    //file might not have downloaded.  Especially if we are offline
                    if (!file.Exists)
                    {
                        this.m_texture = ImageHelper.LoadTexture(file.FullName);
                    }
                    else
                    {
                        this.m_texture = null;
                    }
                }
                else
                {
                    this.m_texture = ImageHelper.LoadTexture(this.m_imageUri);
                }
            }

            this.UpdateVertices();

            this.isInitialized = true;
        }
Beispiel #5
0
		/// <summary>
		/// Loads a bitmap from the web in background and displays.
		/// </summary>
		public void LoadImageInBackground( string url )
		{
			if(url != null && !url.ToLower().StartsWith("http://"))
			{
				// Local file
				Image = Image.FromFile(url);
				return;
			}

			oldText = Text;
			Text = Text + ": Loading...";
			WebDownload client = new WebDownload(url);
		////	client.CompleteCallback += new DownloadCompleteHandler(DownloadComplete);
			client.BackgroundDownloadMemory();
		}
Beispiel #6
0
		/// <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);			
			}
		}
Beispiel #7
0
        private void ProcessInstallEncodedUri()
        {
            //parse install URI
            string urls = worldWindUri.PreserveCase.Substring(20, worldWindUri.PreserveCase.Length - 20);
            urls.Replace(";", ",");
            string[] urllist = urls.Split(',');
            WebDownload zipURL = new WebDownload();

            string zipFilePath = "";

            foreach (string cururl in urllist)
            {
                DialogResult result = MessageBox.Show("Do you want to install the addon from " + cururl + " into World Wind?", "Installing Add-ons", MessageBoxButtons.YesNoCancel);
                switch(result)
                {
                    case DialogResult.Yes:

                        zipFilePath = cururl;   //default to the url
                        //Go ahead and download
                        if (cururl.StartsWith("http"))
                        {
                            try
                            {
                                //It's a web file - download it first
                                zipURL.Url = cururl;
                                zipFilePath = Path.Combine(Path.GetTempPath(), "WWAddon.zip");
                                MessageBox.Show("Click OK to begin downloading.  World Wind may be unresponsive while it is downloading - please wait.","Downloading...");
                                zipURL.DownloadFile(zipFilePath);
                                MessageBox.Show("File downloaded!  Click OK to install.", "File done!");
                            }
                            catch
                            {
                                MessageBox.Show("Could not download file.\nError: " + zipURL.Exception.Message  + "\nURL: " + cururl, "Error");
                            }
                        }

                        try
                        {
                            FastZip fz = new FastZip();
                            fz.ExtractZip(zipFilePath, MainApplication.DirectoryPath, "");
                        }
                        catch
                        {
                            MessageBox.Show("Error installing addon.", "Error");
                        }
                        finally
                        {
                            string addonType = "#";
                            string addonPath = "//";
                            try
                            {
                                string ManifestFile = Path.Combine(MainApplication.DirectoryPath, "manifest.txt");
                                if (File.Exists(ManifestFile))
                                {
                                    StreamReader fs = new StreamReader(ManifestFile);
                                    while (addonType.StartsWith("#") || addonType.StartsWith("//")) { addonType = fs.ReadLine(); }
                                    while (addonPath.StartsWith("#") || addonPath.StartsWith("//")) { addonPath = fs.ReadLine(); }
                                    if (addonType.ToLower().Contains("plugin"))
                                    {
                                        //DoFancyPluginMethod(addonPath);     
                                        MessageBox.Show("Plugin activated: " + addonPath);
                                    }
                                    else {
                                        //DoFancyLayerMethod(addonPath);
                                        //MessageBox.Show("Layer activated: " + addonPath);
										addonPath = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath),
											addonPath);
										LoadAddon(addonPath);
                                    }
                                    fs.Close();
                                    File.Delete(Path.Combine(MainApplication.DirectoryPath, "manifest.txt"));
                                }
                                else
                                {
                                    MessageBox.Show("Add-on manifest not found.  You will have to restart World Wind to use this add-on.", "Restart required");
                                }
                            }
                            catch (Exception e)
                            {
                                MessageBox.Show("Error reading add-on manifest.  You will have to restart World Wind to use this add-on.\nError code: " + e.Message , "Restart required");
                            }

                            try
                            {
                                File.Delete(Path.Combine(Path.GetTempPath(), "WWAddon.zip"));
                            }
                            catch
                            {
                            }
                        }   //end of finally from unzipping
                        break;
                    case DialogResult.No:
                        break;
                    default:
                        return; //They hit cancel - stop downloading stuff
                }
            }
        }
		/// <summary>
		/// Download thread runs this function.
		/// </summary>
		private void Downloader() 
		{
			while(true)
			{
				if(this.animationState == AnimationState.Pending)
				{
					Thread.Sleep(100);
					continue;
				}

				lock(this.downloadQueue)
				{
					if(this.downloadQueue.Count <= 0)
					{
						Thread.Sleep(100);
						continue;
					}
			
					this.wmsDownload = (WMSDownload)this.downloadQueue.Dequeue();
				}

				if(File.Exists(wmsDownload.SavedFilePath)) 
				{
					AddAnimationFrame(wmsDownload);
					return;
				}

				// Download
				try
				{
					this.downloadState = DownloadState.Downloading;
					updateStatusBar( string.Format( CultureInfo.CurrentCulture,
						"Downloading {0} ({1}/{2})",
						wmsDownload.Date,
						this.animationFrames.Count+1,
						this.currentlySelectedLayer.AnimationFrameCount ) );
				
					using( WebDownload dl = new WebDownload( wmsDownload.Url) )
					{
						dl.DownloadType = DownloadType.Wms;
						dl.ProgressCallback += new DownloadProgressHandler(updateCurrentProgressBar);
						dl.DownloadFile(wmsDownload.SavedFilePath);
					}
					Download_CompleteCallback(wmsDownload);
				}
				catch(ThreadAbortException)
				{
					// Normal shutdown
				}
				catch(Exception caught)
				{
					updateStatusBar(caught.Message);
					// Abort download.
					return;
				}
			}
		}
        //TODO: Implement Downloading + Uncompressing + Caching 
        private void DownloadParsePlacenames()
        {
            try
            {
                if (m_failed)
                {
                    return;
                }

				//hard coded cache location wtf?
                //string cachefilename = 
                //    Directory.GetParent(System.Windows.Forms.Application.ExecutablePath) +
                //    string.Format("Cache//WFS//Placenames//{0}//{1}_{2}_{3}_{4}.xml.gz", 
                //    this.name, this.west, this.south, this.east, this.north);
				
				
				//...let's use the location from settings instead
				string cachefilename = m_cache.CacheDirectory +
				    string.Format("\\{0}\\WFS\\{1}\\{2}_{3}_{4}_{5}.xml.gz", 
				    this.m_world.Name, this.name, this.west, this.south, this.east, this.north);
				
                
                if (!File.Exists(cachefilename))
                {
                    WebDownload wfsdl = new WebDownload(this.wfsURL);
                    wfsdl.DownloadFile(cachefilename);
                }
                GZipInputStream instream = new GZipInputStream(new FileStream(cachefilename, FileMode.Open));
                XmlDocument gmldoc = new XmlDocument();
                gmldoc.Load(instream);
                XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(gmldoc.NameTable);
                xmlnsManager.AddNamespace("gml", "http://www.opengis.net/gml");
                //HACK: Create namespace using first part of Label Field
                string labelnmspace = labelfield.Split(':')[0];

                if (labelnmspace == "cite")
                {
                    xmlnsManager.AddNamespace(labelnmspace, "http://www.opengeospatial.net/cite");
                }
                else if(labelnmspace == "topp")
                {
                    xmlnsManager.AddNamespace(labelnmspace, "http://www.openplans.org/topp");
                }

                XmlNodeList featureList = gmldoc.SelectNodes("//gml:featureMember", xmlnsManager);
                if (featureList != null)
                {
                
                    ArrayList placenameList = new ArrayList();
                    foreach (XmlNode featureTypeNode in featureList)
                    {
                        XmlNode typeNameNode = featureTypeNode.SelectSingleNode(typename, xmlnsManager);
                        if (typeNameNode == null)
                        {
                            Log.Write(Log.Levels.Debug, "No typename node: " + typename);
                            continue;
                        }
                        XmlNode labelNode = typeNameNode.SelectSingleNode(labelfield, xmlnsManager);
                        if (labelNode == null)
                        {
                            Log.Write(Log.Levels.Debug, "No label node: " + labelfield);
                            continue;
                        }
                        
                        XmlNodeList gmlCoordinatesNodes = featureTypeNode.SelectNodes(".//gml:Point/gml:coordinates", xmlnsManager);
                        if (gmlCoordinatesNodes != null)
                        {
                            foreach (XmlNode gmlCoordinateNode in gmlCoordinatesNodes)
                            {
                                //Log.Write(Log.Levels.Debug, "FOUND " + gmlCoordinatesNode.Count.ToString() + " POINTS");
                                string coordinateNodeText = gmlCoordinateNode.InnerText;
                                string[] coords = coordinateNodeText.Split(',');
                                WorldWindPlacename pn = new WorldWindPlacename();
                                pn.Lon = float.Parse(coords[0], System.Globalization.CultureInfo.InvariantCulture);
                                pn.Lat = float.Parse(coords[1], System.Globalization.CultureInfo.InvariantCulture);
                                pn.Name = labelNode.InnerText;
                                placenameList.Add(pn);
                            }
                        }
                    }

                    m_placeNames = (WorldWindPlacename[])placenameList.ToArray(typeof(WorldWindPlacename));
                }

                if (m_placeNames == null)
                    m_placeNames = new WorldWindPlacename[0];
            }
            catch //(Exception ex)
            {
                //Log.Write(ex);
                if (m_placeNames == null)
                    m_placeNames = new WorldWindPlacename[0];
                m_failed = true;
            }
        }
Beispiel #10
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;
				}
			}
		}
		/// <summary>
		/// Web download callback for Zips
		/// </summary>
		private void ZipDownloadComplete(WebDownload dl)
		{
			createXmlLoadShape(dl.SavedFilePath);			
			dl.Dispose();
		}
		/// <summary>
		/// Method to load Shape files from shp+shx+dbf supplied in URL
		/// </summary>
		/// <param name="shpURL"></param>
		public void loadXMLFileFromURL(string xmlURL)
		{
			XmlDocument doc=new XmlDocument();
			doc.Load(xmlURL);  
			
			try
			{
				doc.SelectSingleNode
					("/LayerSet/DownloadPage/URL").InnerText=xmlURL;
			}
			catch{/*no timestamp*/}

			string xmlSaveLocation = m_ShapeFileRootDirectory+"\\"+Path.GetFileName(xmlURL);
			string xmlFilesFolder = m_ShapeFileRootDirectory+"\\"
										+Path.GetFileNameWithoutExtension(xmlURL);
			string relFolder=Path.GetFileNameWithoutExtension(xmlURL)+"\\";

			//find a not used name to store the shapefile
			int Nr=1;
			while(File.Exists(xmlSaveLocation)||Directory.Exists(xmlFilesFolder))
			{
				xmlSaveLocation = m_ShapeFileRootDirectory+"\\"+Path.GetFileNameWithoutExtension(xmlURL)
					+"~"+Nr.ToString()+Path.GetExtension(xmlURL);
				xmlFilesFolder = m_ShapeFileRootDirectory+"\\"+Path.GetFileNameWithoutExtension(xmlURL)
					+"~"+Nr.ToString();
				relFolder=Path.GetFileNameWithoutExtension(xmlURL)+"~"+Nr.ToString()+"\\";
				Nr++;
			}		

			XmlNodeList namelist = doc.GetElementsByTagName("ShapeFilePath");

			ArrayList filePaths = new ArrayList();
			filePaths.Add(xmlSaveLocation);

			string xmlFolder=xmlURL.Remove(1+xmlURL.LastIndexOfAny(new char[]{'/','\\'}),
				xmlURL.Length-1-xmlURL.LastIndexOfAny(new char[]{'/','\\'}));			
			//get the paths to the xml related files
			foreach(XmlNode node in namelist)
			{
				if(!filePaths.Contains(xmlFolder+node.InnerText))	
				{
					if(node.InnerText.ToLower().EndsWith(".shp"))
					{
						filePaths.Add(xmlFolder+node.InnerText);
						filePaths.Add(xmlFolder+node.InnerText.Replace(".shp",".dbf"));
					}
					else
						filePaths.Add(xmlFolder+node.InnerText);
				}								
				node.InnerText=relFolder+Path.GetFileName(node.InnerText);
			}

			//Save xml
			doc.Save(xmlSaveLocation);

			//download relative files and load xml
			if(filePaths.Count!=1)
				Directory.CreateDirectory(xmlFilesFolder);			

			xmlDownloads.Add(filePaths);

			WebDownload[] wd=new WebDownload[filePaths.Count-1];
			for(int i=1; i< filePaths.Count; i++)
			{					
				wd[i-1]= new WebDownload(((string)filePaths[i]));
				wd[i-1].CompleteCallback += new DownloadCompleteHandler(xmlRelatedFileDownloadComplete);			
				wd[i-1].SavedFilePath = xmlFilesFolder+"\\"+Path.GetFileName(((string)filePaths[i]));				
				wd[i-1].BackgroundDownloadFile();
			}			
		}
		/// <summary>
		/// Method to load Shape files from shape+xml zip packs supplied in URL
		/// </summary>
		/// <param name="zipURL"></param>
		public void loadZipFileFromURL(string zipURL)
		{
			
			string zippath = m_ShapeFileRootDirectory+"\\"+Path.GetFileName(zipURL);
			int Nr=1;
			while(File.Exists(zippath))
			{
				zippath = m_ShapeFileRootDirectory+"\\"+Path.GetFileNameWithoutExtension(zipURL)
					+"~"+Nr.ToString()+Path.GetExtension(zipURL);
				Nr++;
			}

			WebDownload dl = new WebDownload(zipURL);
			dl.CompleteCallback += new DownloadCompleteHandler(ZipDownloadComplete);
			dl.SavedFilePath = zippath;
			actualDownloads.Add(dl);
			dl.BackgroundDownloadFile();
		
		}
Beispiel #14
0
 /// <summary>
 /// Called with detailed information about the download.
 /// </summary>
 /// <param name="wd">The WebDownload.</param>
 private static void OnDebugCallback(WebDownload wd)
 {
     if (DebugCallback != null) {
         DebugCallback(wd);
     }
 }
Beispiel #15
0
		public void DownloadImageListUpdate()
		{
			string imageListURL = "http://rapidfire.sci.gsfc.nasa.gov/gallery/WWinventory.txt";
			try
			{
				this.loadSavedFileList(CacheDirectory + "\\CachedModisListNew.txt");
				this.UpdateIcons();
				if(File.Exists(this.imageListFilePath))
				{
					this.labelStatus.Text = "Parsing cached image list...";
					this.parseImageListFile(this.imageListFilePath);
					this.UpdateIcons();
				}

				this.labelStatus.Text = "Downloading new image list...";
				using( WebDownload webDownload = new WebDownload(imageListURL) )
				{
					webDownload.ProgressCallback += new DownloadProgressHandler(updateProgressBar);
					webDownload.DownloadFile(this.imageListFilePath);
				}

				this.labelStatus.Text = "Parsing cached image list...";

				this.parseImageListFile(this.imageListFilePath);
				this.UpdateIcons();

				this.labelStatus.Text = "";
				this.progressBar.Value = 0;
			}
			catch(ThreadAbortException)
			{
				// Shut down by user
			}
			catch(Exception caught)
			{
				Log.Write(caught);
			}
		}
Beispiel #16
0
        protected override void DownloadComplete(WebDownload downloadInfo)
        {
            try
             {
            downloadInfo.Verify();

            if (downloadInfo.Exception != null)
            {
               Log.Write(downloadInfo.Exception);
               return;
            }

            XmlDocument hResponseDocument = new XmlDocument();
            XmlReaderSettings oSettings = new XmlReaderSettings();
            oSettings.IgnoreWhitespace = true;
            XmlReader oResponseXmlStream = XmlReader.Create(downloadInfo.ContentStream, oSettings);
            hResponseDocument.Load(oResponseXmlStream);
            downloadInfo.ContentStream.Close();

            // Get the URL, save the image
            XmlElement nOutputElement = hResponseDocument.SelectSingleNode("/ARCXML/RESPONSE/IMAGE/OUTPUT") as XmlElement;
            if (nOutputElement != null)
            {
               String imageURL = nOutputElement.GetAttribute("url");
               Log.Write(Log.Levels.Debug, "ADGR", "Downloading file " + imageURL);
               // ---------------------------
               downloadImage(imageURL, downloadInfo.SavedFilePath);
            }
            else
            {
               XmlElement nErrorElement = hResponseDocument.SelectSingleNode("/ARCXML/RESPONSE/ERROR") as XmlElement;
                    if (nErrorElement != null)
                        Log.Write(Log.Levels.Debug, "ADGR", nErrorElement.InnerText);
            }

            m_tile.TileSet.NumberRetries = 0;
            if (nOutputElement != null)
            {
               // Rename temp file to real name
               File.Delete(m_localFilePath);

               // Convert the image to a PNG from a GIF so DirectX doesn't throw a hissy fit trying to load gifs
               if (downloadInfo.SavedFilePath.EndsWith(".gif"))
               {
                  Image oConverter = Image.FromFile(downloadInfo.SavedFilePath);
                  oConverter.Save(m_localFilePath, System.Drawing.Imaging.ImageFormat.Png);
                  oConverter.Dispose();
                  File.Delete(downloadInfo.SavedFilePath);
               }
               else
               {
                  File.Move(downloadInfo.SavedFilePath, m_localFilePath);
               }

               // Make the tile reload the new image
               m_tile.DownloadRequests.Remove(this);
               m_tile.Initialize();
            }
            else
            {
               using (File.Create(m_localFilePath + ".txt"))
               { }
               if (File.Exists(downloadInfo.SavedFilePath))
               {
                  try
                  {
                     File.Delete(downloadInfo.SavedFilePath);
                  }
                  catch (Exception e)
                  {
                     Log.Write(e);
                  }
               }
            }
             }
             catch (System.Net.WebException caught)
             {
            System.Net.HttpWebResponse response = caught.Response as System.Net.HttpWebResponse;
            if (response != null && response.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
               using (File.Create(m_localFilePath + ".txt"))
               { }
               return;
            }
            m_tile.TileSet.NumberRetries++;
             }
             catch
             {
            using (File.Create(m_localFilePath + ".txt"))
            { }
            if (File.Exists(downloadInfo.SavedFilePath))
            {
               try
               {
                  File.Delete(downloadInfo.SavedFilePath);
               }
               catch (Exception e)
               {
                  Log.Write(e);
               }
            }
             }
             finally
             {
            if (download != null)
               download.IsComplete = true;

            // Immediately queue next download
            m_tile.TileSet.RemoveFromDownloadQueue(this, true);
             }
        }
Beispiel #17
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="owner">The object owning this request.</param>
 /// <param name="url">The URL to download from.</param>
 public WebDownloadRequest(object owner, string url) : base(owner)
 {
     download = new WebDownload(url);
 }
Beispiel #18
0
 /// <summary>
 /// Called when downloading has ended.
 /// </summary>
 /// <param name="wd">The download.</param>
 private static void OnDownloadEnded(WebDownload wd)
 {
     if (DownloadEnded != null) {
         DownloadEnded(wd);
     }
 }
		/// <summary>
		/// Method to load Shape files from shp+dbf supplied in URL
		/// </summary>
		/// <param name="shpURL"></param>
		public void loadShpFileFromURL(string shpURL)
		{		
			string shppath = m_ShapeFileRootDirectory+"\\"+Path.GetFileName(shpURL);
	
			int Nr=1;
			while(File.Exists(shppath)||File.Exists(Path.ChangeExtension(shppath,".dbf")))
			{
				shppath = m_ShapeFileRootDirectory+"\\"+Path.GetFileNameWithoutExtension(shpURL)
					+"~"+Nr.ToString()+Path.GetExtension(shpURL);
				Nr++;
			}		
						
			WebDownload dl1 = new WebDownload(shpURL);
			WebDownload dl3 = new WebDownload(Path.ChangeExtension(shpURL,".dbf"));

			dl1.CompleteCallback += new DownloadCompleteHandler(ShpDownloadComplete);			
			dl1.SavedFilePath = shppath;
			actualDownloads.Add(dl1);
			dl1.BackgroundDownloadFile();
			
			dl3.CompleteCallback += new DownloadCompleteHandler(ShpDownloadComplete);			
			dl3.SavedFilePath = Path.ChangeExtension(shppath,".dbf");
			actualDownloads.Add(dl3);
			dl3.BackgroundDownloadFile();

		}	
Beispiel #20
0
 private void DownloadComplete(WebDownload oDownload)
 {
     // --- Sending it is what matters, we don't care what comes back ---
     oDownload.Dispose();
 }
		/// <summary>
		/// Web download callback for shp+shx+dbf
		/// </summary>
		private void ShpDownloadComplete(WebDownload dl)
		{
			if(dl.SavedFilePath.ToLower().EndsWith(".shp"))
			{
				for(int i=0; i<actualDownloads.Count; i++)
				{
					if( ((WebDownload)actualDownloads[i]).SavedFilePath==
						Path.ChangeExtension(dl.SavedFilePath,".dbf"))
					{
						if( ((WebDownload)actualDownloads[i]).IsComplete )
						{
							((WebDownload)actualDownloads[i]).Dispose();
							actualDownloads.RemoveAt(i);
							createXmlLoadShape(dl.SavedFilePath);
						}
						else
							return;
					}				
				}
			}
			else 
			{
				for(int i=0; i<actualDownloads.Count; i++)
				{
					if( ((WebDownload)actualDownloads[i]).SavedFilePath==
						Path.ChangeExtension(dl.SavedFilePath,".shp"))
					{
						if( ((WebDownload)actualDownloads[i]).IsComplete )
						{
							((WebDownload)actualDownloads[i]).Dispose();
							actualDownloads.RemoveAt(i);
							createXmlLoadShape(Path.ChangeExtension(dl.SavedFilePath,".shp"));
						}
						else
							return;
					}				
				}
			}						
			dl.Dispose();
		}
		/// <summary>
		/// Override to be notified when download has completed.
		/// </summary>
		protected virtual void InternalDownloadComplete(WebDownload download)
		{
			try
			{
				DownloadComplete();
			}
			catch(Exception caught)
			{
				Log.Write(Log.Levels.Error, "QUEU", download.Url + ": " + caught.Message);
			}

			OnComplete();
		}
		/// <summary>
		/// Web download callback for Files relative to a xml
		/// used by loadXMLFileFromURL
		/// </summary>
		private void xmlRelatedFileDownloadComplete(WebDownload dl)
		{	
			for(int i=0; i<xmlDownloads.Count; i++)
			{	
				for(int u=1; u<((ArrayList)(xmlDownloads[i])).Count; u++)//xmlDownloads[0] is the xml path
				{					
					if(((string)((ArrayList)(xmlDownloads[i]))[u]) ==
						dl.Url)
					{						
						((ArrayList)(xmlDownloads[i])).RemoveAt(u);
						if(((ArrayList)(xmlDownloads[i])).Count <= 1)
						{								
							//load xml (all files have been downloaded)
							loadShapeFileWithAlreadyExistingXML(
								((string)((ArrayList)(xmlDownloads[i]))[0]),false);
							xmlDownloads.RemoveAt(i);
						}
					}
				}
				
			}

			dl.Dispose();
		}
		public override void Dispose()
		{
			try
			{
				if(download != null)
				{
					download.Dispose();
					download = null;
				}
			}
			finally
			{
				base.Dispose();
			}
		}
Beispiel #25
0
        private void m_RefreshTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (isUpdating) {
                return;
            }

            isUpdating = true;

            if (m_ImageUri == null) {
                return;
            }

            if (m_ImageUri.ToLower().StartsWith("http://")) {
                if (m_SaveFilePath == null) {
                    return;
                }

                //download it
                try {
                    WebDownload webDownload = new WebDownload(m_ImageUri);
                    webDownload.DownloadType = DownloadType.Unspecified;

                    FileInfo saveFile = new FileInfo(m_SaveFilePath);
                    if (!saveFile.Directory.Exists) {
                        saveFile.Directory.Create();
                    }

                    webDownload.DownloadFile(m_SaveFilePath);
                }
                catch {}
            }
            else {
                m_SaveFilePath = m_ImageUri;
            }

            if (m_ImageTexture != null
                && !m_ImageTexture.Disposed) {
                m_ImageTexture.Dispose();
                m_ImageTexture = null;
            }

            if (!File.Exists(m_SaveFilePath)) {
                displayText = "Image Not Found";
                return;
            }

            m_ImageTexture = ImageHelper.LoadTexture(m_SaveFilePath);
            m_surfaceDescription = m_ImageTexture.GetLevelDescription(0);

            int width = ClientSize.Width;
            int height = ClientSize.Height;

            if (ClientSize.Width == 0) {
                width = m_surfaceDescription.Width;
            }
            if (ClientSize.Height == 0) {
                height = m_surfaceDescription.Height;
            }

            if (ParentWidget is Form) {
                Form parentForm = (Form) ParentWidget;
                parentForm.ClientSize = new Size(width, height + parentForm.HeaderHeight);
            }
            else {
                ParentWidget.ClientSize = new Size(width, height);
            }

            ClientSize = new Size(width, height);

            IsLoaded = true;
            isUpdating = false;
            displayText = null;
            if (m_RefreshTime == 0) {
                m_RefreshTimer.Stop();
            }
        }
		/// <summary>
		/// Initializes a new instance of the <see cref= "T:WorldWind.Net.WebDownloadRequest"/> class.
		/// </summary>
		/// <param name="owner">The object owning this request.</param>
		public WebDownloadRequest(object owner) : base(owner)
		{
			download = new WebDownload("");
		}
		/// <summary>
		/// Constructor.
		/// </summary>
		/// <param name="owner">The object owning this request.</param>
		/// <param name="url">The URL to download from.</param>
		public WebDownloadRequest(object owner, string url) : base(owner)
		{
			download = new WebDownload(url);
		}
        private void DownloadComplete(WebDownload downloadInfo)
        {
            try {
                downloadInfo.Verify();

                m_quadTile.QuadTileSet.NumberRetries = 0;

                // Rename temp file to real name
                File.Delete(m_localFilePath);
                File.Move(downloadInfo.SavedFilePath, m_localFilePath);

                // Make the quad tile reload the new image
                m_quadTile.DownloadRequest = null;
                m_quadTile.Initialize();
            }
            catch (WebException caught) {
                HttpWebResponse response = caught.Response as HttpWebResponse;
                if (response != null
                    && response.StatusCode == HttpStatusCode.NotFound) {
                    using (File.Create(m_localFilePath + ".txt")) {}
                    return;
                }
                m_quadTile.QuadTileSet.NumberRetries++;
            }
            catch {
                using (File.Create(m_localFilePath + ".txt")) {}
                if (File.Exists(downloadInfo.SavedFilePath)) {
                    File.Delete(downloadInfo.SavedFilePath);
                }
            }
            finally {
                #region by zzm
                if (download != null) {
                    download.IsComplete = true;
                }
                #endregion

                m_quadTile.QuadTileSet.RemoveFromDownloadQueue(this);

                //Immediately queue next download
                m_quadTile.QuadTileSet.ServiceDownloadQueue();
            }
        }
		/// <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);
		}
 public virtual void Dispose()
 {
     if (download != null) {
         download.Dispose();
         download = null;
     }
     GC.SuppressFinalize(this);
 }
        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 = "";
            }

        }
 public virtual void StartDownload()
 {
     QuadTile.IsDownloadingImage = true;
     download = new WebDownload(m_url);
     download.DownloadType = DownloadType.Wms;
     download.SavedFilePath = m_localFilePath + ".tmp";
     download.ProgressCallback += new DownloadProgressHandler(UpdateProgress);
     download.CompleteCallback += new DownloadCompleteHandler(DownloadComplete);
     download.BackgroundDownloadFile();
 }
		/// <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;
		}
Beispiel #34
0
 /// <summary>
 /// Initializes a new instance of the <see cref= "T:WorldWind.Net.WebDownloadRequest"/> class.
 /// </summary>
 /// <param name="owner">The object owning this request.</param>
 public WebDownloadRequest(object owner) : base(owner)
 {
     download = new WebDownload("");
 }