示例#1
0
 internal void NotifyDecideDestinationWithSuggestedFilename(WebDownload download, string fileName)
 {
     if (FilePath.Length != 0)
         download.setDestination(FilePath, 1);
     else
         download.setDestination(fileName, 1);
 }
示例#2
0
 public void Setup()
 {
     MockBuild buildEngine = new MockBuild();
     testDirectory = TaskUtility.makeTestDirectory(buildEngine);
     task = new WebDownload();
     task.BuildEngine = new MockBuild();
 }
		public PackageDownload(string urlRoot, string displayName, Hash hash, SpringPaths paths)
		{
			this.paths = paths;
			this.urlRoot = urlRoot;
			pool = new Pool(paths);

			PackageHash = hash;
			Name = displayName;
			fileListWebGet = new WebDownload();
		}
示例#4
0
        public void WebDownloadExecute()
        {
            WebDownload task = new WebDownload();
            task.BuildEngine = new MockBuild();
            task.FileUri = "http://www.microsoft.com/default.aspx";
            string downloadFile = Path.Combine(testDirectory, "microsoft.html");
            task.FileName = downloadFile;
            Assert.IsTrue(task.Execute(), "Execute Failed");

            Assert.IsTrue(File.Exists(downloadFile), "No download file");
        }
示例#5
0
        public void PassArguments(string filename, Int64 filesize, WebDownload d)
        {

            this.Size = filesize;
            this.File = filename;
            this.download = d;
            this.FileForDownloading = filename + ".download";
            label5.Text = "Size: " + Size.ToString();
            label2.Text = Path.GetFileName(File);
            progressBar1.Maximum = Convert.ToInt32(filesize);
            progressBar1.Minimum = 0;
            UpdateProgress.Enabled = true;
        }
示例#6
0
    protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        Int32 index = 0;
        if (!Int32.TryParse("" + e.CommandArgument, out index)) index = -1;
        Int32 id = index >= 0 ? (Int32)gv.DataKeys[index][0] : 0;
        DataModel md = DataModel.FindByID(id);

        if (md != null)
        {
            if (e.CommandName == "ExportXml")
            {
                String xml = md.ExportXml();
                if (!String.IsNullOrEmpty(xml))
                {
                    //MemoryStream ms = new MemoryStream();
                    //EntityAccessorFactory.Create(EntityAccessorTypes.Xml)
                    //    .SetConfig(EntityAccessorOptions.Stream, ms)
                    //    .Write(md, null);
                    //ms.Position = 0;
                    WebDownload wd = new WebDownload();
                    MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xml));
                    wd.Stream = ms;
                    wd.FileName = md.Name + ".xml";
                    wd.Mode = WebDownload.DispositionMode.Attachment;
                    wd.Render();
                    Response.End();
                }
            }
            else if (e.CommandName == "ExportZip")
            {
                MemoryStream ms = new MemoryStream();
                md.ExportZip(ms);

                WebDownload wd = new WebDownload();
                wd.Stream = ms;
                wd.FileName = md.Name + ".zip";
                wd.Mode = WebDownload.DispositionMode.Attachment;
                wd.Render();
                Response.End();
            }
        }
    }
 public void didFinish(WebDownload download)
 {
     DidFinish(download);
 }
 public void didCreateDestination(WebDownload download, string destination)
 {
     DidCreateDestination(download, destination);
 }
 public void didBegin(WebDownload download)
 {
     DidBegin(download);
 }
 public void willSendRequest(WebDownload download, WebMutableURLRequest request, WebURLResponse redirectResponse, out WebMutableURLRequest finalRequest)
 {
     finalRequest = request;
 }
 public int shouldDecodeSourceDataOfMIMEType(WebDownload download, string encodingType)
 {
     // TODO
     return 0;
 }
示例#12
0
 private void downloadDelegate_DecideDestinationWithSuggestedFilename(WebDownload download, string fileName)
 {
     downloads[download].NotifyDecideDestinationWithSuggestedFilename(download, fileName);
 }
示例#13
0
        //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;
            }
        }
示例#14
0
 public void didReceiveResponse(WebDownload download, WebURLResponse response)
 {
 }
示例#15
0
 public void didReceiveDataOfLength(WebDownload download, uint length)
 {
 }
示例#16
0
 public void didReceiveAuthenticationChallenge(WebDownload download, IWebURLAuthenticationChallenge challenge)
 {
 }
示例#17
0
 public void didFinish(WebDownload download)
 {
 }
示例#18
0
 public void didFailWithError(WebDownload download, WebError error)
 {
 }
示例#19
0
 public void didCreateDestination(WebDownload download, string destination)
 {
 }
示例#20
0
 public void didCancelAuthenticationChallenge(WebDownload download, IWebURLAuthenticationChallenge challenge)
 {
 }
示例#21
0
 internal void NotifyDidFailWithError(WebDownload download, WebError error)
 {
     // Todo
 }
示例#22
0
        /// <summary>
        /// Downloads a KML/KMZ file from the given URL
        /// </summary>
        private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (this.bUpdating)
            {
                return;
            }
            this.bUpdating = true;

            try
            {
                if (!this.m_firedStartup || (this.layer != null && this.layer.IsOn))
                {
                    string fullurl = this.url;
                    if (sender == this.viewTimer)
                    {
                        if (!this.bViewStopped)
                        {
                            if (DrawArgs.Camera.ViewMatrix != this.lastView)
                            {
                                this.lastView  = DrawArgs.Camera.ViewMatrix;
                                this.bUpdating = false;
                                return;
                            }

                            this.bViewStopped = true;
                        }
                        else
                        {
                            if (DrawArgs.Camera.ViewMatrix != this.lastView)
                            {
                                this.lastView     = DrawArgs.Camera.ViewMatrix;
                                this.bViewStopped = false;
                            }

                            this.bUpdating = false;
                            return;
                        }
                        fullurl += (fullurl.IndexOf('?') == -1 ? "?" : "&") + GetBBox();
                    }

                    string saveFile = Path.GetFileName(Uri.EscapeDataString(this.url));
                    if (saveFile == null || saveFile.Length == 0)
                    {
                        saveFile = "temp.kml";
                    }

                    saveFile = Path.Combine(KMLParser.KmlDirectory + "\\temp\\", saveFile);

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

                    // Offline check
                    if (World.Settings.WorkOffline)
                    {
                        throw new Exception("Offline mode active.");
                    }

                    WebDownload myClient = new WebDownload(fullurl);
                    myClient.DownloadFile(saveFile);

                    // Extract the file if it is a kmz file
                    string kmlFile = saveFile;

                    // Create a reader to read the file
                    KMLLoader loader = new KMLLoader();
                    if (Path.GetExtension(saveFile) == ".kmz")
                    {
                        bool bError = false;
                        kmlFile = loader.ExtractKMZ(saveFile, out bError);

                        if (bError)
                        {
                            return;
                        }
                    }

                    // Read all data from the reader
                    string kml = loader.LoadKML(kmlFile);

                    if (kml != null)
                    {
                        try
                        {
                            // Load the actual kml data
                            this.owner.ReadKML(kml, this.layer, kmlFile);
                        }
                        catch (Exception ex)
                        {
                            Log.Write(Log.Levels.Error, "KMLParser: " + ex.ToString());

                            MessageBox.Show(
                                String.Format(CultureInfo.InvariantCulture, "Error loading KML file '{0}':\n\n{1}", kmlFile, ex.ToString()),
                                "KMLParser error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error,
                                MessageBoxDefaultButton.Button1,
                                MessageBoxOptions.ServiceNotification);
                        }
                    }

                    this.m_firedStartup = true;
                }
            }
            catch (Exception ex)
            {
                Log.Write(Log.Levels.Error, "KMLParser: " + ex.ToString());
            }

            this.bUpdating = false;
        }
示例#23
0
 public int shouldDecodeSourceDataOfMIMEType(WebDownload download, string encodingType)
 {
     throw new NotImplementedException();
 }
示例#24
0
 private void downloadDelegate_DidFinish(WebDownload download)
 {
     downloads[download].NotifyDidFinish(download);
     // remove from list
     downloads.Remove(download);
 }
示例#25
0
 public void willResumeWithResponse(WebDownload download, WebURLResponse response, long fromByte)
 {
 }
示例#26
0
 public void didBegin(WebDownload download)
 {
 }
示例#27
0
 public void willSendRequest(WebDownload download, WebMutableURLRequest request, WebURLResponse redirectResponse, out WebMutableURLRequest finalRequest)
 {
     throw new NotImplementedException();
 }
 public void willResumeWithResponse(WebDownload download, WebURLResponse response, long fromByte)
 {
     WillResumeWithResponse(download, response, fromByte);
 }
示例#29
0
 public void decideDestinationWithSuggestedFilename(WebDownload download, string fileName)
 {
 }
 public void decideDestinationWithSuggestedFilename(WebDownload download, string fileName)
 {
     DecideDestinationWithSuggestedFilename(download, fileName);
 }
示例#31
0
        /// <summary>
        /// Updates the specified download.
        /// </summary>
        /// <param name="wd">The wd.</param>
        public void Update(WebDownload wd)
        {
            // Make sure we're on the right thread
            if (this.InvokeRequired)
            {
                try
                {
                    // Update progress asynchronously
                    DownloadCompleteHandler dlgt = new DownloadCompleteHandler(Update);
                    this.Invoke(dlgt, new object[] { wd });
                }
                catch (Exception ex)
                {
                    Log.Write(ex);
                }
                return;
            }

            foreach (DebugItem item in listView.Items)
            {
                if (item.WebDownload == wd)
                {
                    item.Update(wd);

                    if (logToFile)
                    {
                        if (wd.Exception != null)
                        {
                            Log.Write(Log.Levels.Error, logCategory, "Error : " + wd.Url.Replace("http://", ""));
                            Log.Write(Log.Levels.Error, logCategory, "  \\---" + wd.Exception.Message);
                        }
                        if (wd.ContentLength == wd.BytesProcessed)
                        {
                            string msg = string.Format(CultureInfo.CurrentCulture,
                                                       "Done ({0:f2}s): {1}",
                                                       item.ElapsedTime.TotalSeconds,
                                                       wd.Url.Replace("http://", ""));
                            Log.Write(Log.Levels.Debug, logCategory, msg);
                        }
                    }
                    return;
                }
            }
            if (!isRunning)
            {
                return;
            }

            if (listView.Items.Count >= maxItems)
            {
                RemoveOldestItem();
            }

            if (logToFile)
            {
                Log.Write(Log.Levels.Debug, logCategory, "Get  : " + wd.Url);
                if (wd.SavedFilePath != null)
                {
                    Log.Write(Log.Levels.Debug + 1, logCategory, "  \\--- " + wd.SavedFilePath);
                }
            }

            DebugItem newItem = new DebugItem(wd);

            newItem.Update(wd);
            listView.Items.Insert(0, newItem);
        }
 public void didCancelAuthenticationChallenge(WebDownload download, IWebURLAuthenticationChallenge challenge)
 {
     DidCancelAuthenticationChallenge(download, challenge);
 }
        public static async Task <bool> GetItemsFromJsonAsync()
        {
            var url = ItemListSourceUrl;

            if (string.IsNullOrEmpty(ItemListSourceUrl))
            {
                url = Settings.Default.DefaultItemListSourceUrl;
                if (string.IsNullOrEmpty(url))
                {
                    return(false);
                }

                var ini = new IniFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Settings.Default.SettingsFileName));
                ini.WriteValue("Settings", "ItemListSourceUrl", url);
                MessageBox.Show(LanguageController.Translation("DEFAULT_ITEMLIST_HAS_BEEN_LOADED"), LanguageController.Translation("NOTE"));
            }

            if (File.Exists($"{AppDomain.CurrentDomain.BaseDirectory}{Settings.Default.ItemListFileName}"))
            {
                var fileDateTime = File.GetLastWriteTime($"{AppDomain.CurrentDomain.BaseDirectory}{Settings.Default.ItemListFileName}");

                if (fileDateTime.AddDays(7) < DateTime.Now)
                {
                    using (var wc = new WebClient())
                    {
                        var itemString = await wc.DownloadStringTaskAsync(url);

                        File.WriteAllText($"{AppDomain.CurrentDomain.BaseDirectory}{Settings.Default.ItemListFileName}", itemString, Encoding.UTF8);

                        try
                        {
                            Items = JsonConvert.DeserializeObject <List <Item> >(itemString);
                        }
                        catch (Exception ex)
                        {
                            Debug.Print(ex.Message);
                            Items = null;
                            return(false);
                        }
                        return(true);
                    }
                }

                try
                {
                    var localItemString = File.ReadAllText($"{AppDomain.CurrentDomain.BaseDirectory}{Settings.Default.ItemListFileName}");
                    Items = JsonConvert.DeserializeObject <List <Item> >(localItemString);
                }
                catch (Exception ex)
                {
                    Debug.Print(ex.Message);
                    Items = null;
                    return(false);
                }

                return(true);
            }

            using (var wd = new WebDownload(30000))
            {
                try
                {
                    var itemsString = await wd.DownloadStringTaskAsync(url);

                    File.WriteAllText($"{AppDomain.CurrentDomain.BaseDirectory}{Settings.Default.ItemListFileName}", itemsString, Encoding.UTF8);
                    Items = JsonConvert.DeserializeObject <List <Item> >(itemsString);
                    return(true);
                }
                catch (Exception)
                {
                    try
                    {
                        var itemsString = await wd.DownloadStringTaskAsync(Settings.Default.DefaultItemListSourceUrl);

                        File.WriteAllText($"{AppDomain.CurrentDomain.BaseDirectory}{Settings.Default.ItemListFileName}", itemsString, Encoding.UTF8);
                        Items = JsonConvert.DeserializeObject <List <Item> >(itemsString);
                        return(true);
                    }
                    catch (Exception)
                    {
                        return(false);
                    }
                }
            }
        }
 public void didFailWithError(WebDownload download, WebError error)
 {
     DidFailWithError(download, error);
 }
示例#35
0
 private void downloadDelegate_DidFailWithError(WebDownload download, WebError error)
 {
     downloads[download].NotifyDidFailWithError(download, error);
 }
示例#36
0
 internal void NotifyDidReceiveResponse(WebDownload download, WebURLResponse response)
 {
     DownloadStarted(this, new DownloadStartedEventArgs(response.suggestedFilename(), response.expectedContentLength()));
 }
示例#37
0
 private void downloadDelegate_DidFinish(WebDownload download)
 {
     downloads[download].NotifyDidFinish(download);
     // remove from list
     downloads.Remove(download);
 }
示例#38
0
 internal void NotifyDidFinish(WebDownload download)
 {
     DownloadFinished(this, new DownloadFinishedEventArgs());
 }
示例#39
0
 private void downloadDelegate_DidReceiveResponse(WebDownload download, WebURLResponse response)
 {
     downloads[download].NotifyDidReceiveResponse(download, response);
 }
示例#40
0
 internal bool NotifyDidReceiveDataOfLength(WebDownload download, uint length)
 {
     if (DidCancel)
     {
         download.cancel();
         return false;
     }
     else
     {
         DownloadReceiveData(this, new DownloadReceiveDataEventArgs(length));
         return true;
     }
 }
示例#41
0
        private void downloadDelegate_DecideDestinationWithSuggestedFilename(WebDownload download, string fileName)
        {
            download.setDeletesFileUponFailure(1);
            if (string.IsNullOrEmpty(fileName) == false)
            {
                string url = download.request().url();
                if (GlobalPreferences.WillHandleDownloadsManually)
                {
                    FileDownloadBeginEventArgs args = new FileDownloadBeginEventArgs(download.request().url(), fileName, download);
                    DownloadBegin(this, args);
                }
                else
                {
                    if (!(canornot == download))
                    {
                        canornot = download;
                        candownload = "yes";
                    }
                    else { canornot = null; }
                    if (!url.StartsWith("file://"))
                        foreach (Form hello in Application.OpenForms)
                        {
                            if (hello.Name == "MainDownloadForm")
                            {
                                candownload = "no";
                            }
                        }
                    if (candownload == "yes")
                    {
                        MyDownloader.App.UI.MainDownloadForm newd = new MyDownloader.App.UI.MainDownloadForm();
                        newd.Show();
                        newd.downloadList1.NewFileDownload(url, fileName, true, false);
                    }
                    else
                    {
                        ((MyDownloader.App.UI.MainDownloadForm)Application.OpenForms["MainDownloadForm"]).Show();
                        ((MyDownloader.App.UI.MainDownloadForm)Application.OpenForms["MainDownloadForm"]).downloadList1.NewFileDownload(url, fileName, true, false);

                    }
                    download.cancelForResume();
                }
            }
        }
示例#42
0
 private void downloadDelegate_DidFailWithError(WebDownload download, WebError error)
 {
     downloads[download].NotifyDidFailWithError(download, error);
 }
示例#43
0
 private void DownloadComplete(WebDownload oDownload)
 {
     // --- Sending it is what matters, we don't care what comes back ---
     oDownload.Dispose();
 }
示例#44
0
        private void downloadDelegate_DidBegin(WebDownload download)
        {
            // create WebKitDownload object to handle this download and notify listeners
            WebKitDownload d = new WebKitDownload();
            downloads.Add(download, d);

            FileDownloadBeginEventArgs args = new FileDownloadBeginEventArgs(d);
            DownloadBegin(this, args);

            if (args.Cancel)
                d.Cancel();
        }
 public void didReceiveResponse(WebDownload download, WebURLResponse response)
 {
     DidReceiveResponse(download, response);
 }
示例#46
0
 private void downloadDelegate_DidReceiveDataOfLength(WebDownload download, uint length)
 {
     // returns false if we cancelled the download at this point
     if (!downloads[download].NotifyDidReceiveDataOfLength(download, length))
         downloads.Remove(download);
 }
示例#47
0
        private void UpdateImages()
        {
            try
            {
                System.Collections.ArrayList remoteImageList = new System.Collections.ArrayList();

                try
                {
                    // Offline check
                    if (World.Settings.WorkOffline)
                    {
                        throw new Exception("Offline mode active.");
                    }

                    WebDownload download         = new WebDownload(m_remoteUrl);
                    FileInfo    currentIndexFile = new FileInfo(m_imageDirectoryPath + "\\current.txt");
                    if (!currentIndexFile.Directory.Exists)
                    {
                        currentIndexFile.Directory.Create();
                    }

                    download.DownloadFile(currentIndexFile.FullName, DownloadType.Unspecified);
                    download.Dispose();

                    using (StreamReader reader = currentIndexFile.OpenText())
                    {
                        string data = reader.ReadToEnd();

                        string[] parts = data.Split('"');

                        for (int i = 0; i < parts.Length; i++)
                        {
                            if (parts[i].StartsWith("/GlobalCloudsArchive/PastDay/"))
                            {
                                remoteImageList.Add(parts[i].Replace("/GlobalCloudsArchive/PastDay/", ""));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Write(ex);
                }

                System.Collections.ArrayList imageDisplayList = new System.Collections.ArrayList();

                DirectoryInfo cloudImageDirectory = new DirectoryInfo(m_imageDirectoryPath);

                FileInfo[] archiveImageFiles = new FileInfo[0];

                if (cloudImageDirectory.Exists)
                {
                    archiveImageFiles = cloudImageDirectory.GetFiles("*.png");
                }

                for (int i = remoteImageList.Count - 1; i >= 0; i--)
                {
                    string currentRemoteFile = (string)remoteImageList[i];

                    bool found = false;
                    for (int j = 0; j < archiveImageFiles.Length; j++)
                    {
                        if (archiveImageFiles[j].Name == currentRemoteFile.Replace(".jpg", ".png"))
                        {
                            found = true;
                        }
                    }

                    if (!found)
                    {
                        // Offline check
                        if (World.Settings.WorkOffline)
                        {
                            throw new Exception("Offline mode active.");
                        }

                        FileInfo    jpgFile  = new FileInfo(cloudImageDirectory.FullName + "\\" + currentRemoteFile);
                        WebDownload download = new WebDownload(
                            m_remoteUrl + "/" + currentRemoteFile);

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

                        download.DownloadFile(jpgFile.FullName, DownloadType.Unspecified);

                        ImageHelper.CreateAlphaPngFromBrightness(jpgFile.FullName, jpgFile.FullName.Replace(".jpg", ".png"));
                    }
                }

                //reload the list of downloaded images
                if (cloudImageDirectory.Exists)
                {
                    archiveImageFiles = cloudImageDirectory.GetFiles("*.png");
                }

                for (int i = archiveImageFiles.Length - 1; i >= 0; i--)
                {
                    imageDisplayList.Insert(0, archiveImageFiles[i].FullName);
                }

                double north = 90, south = -90, west = -180, east = 180;

                for (int i = 0; i < imageDisplayList.Count; i++)
                {
                    string currentImageFile = (string)imageDisplayList[i];

                    string ddsFilePath = currentImageFile.Replace(".png", ".dds");
                    if (!File.Exists(ddsFilePath))
                    {
                        ImageHelper.ConvertToDxt3(currentImageFile, ddsFilePath, false);
                    }
                    DynamicCloudFrame frame = new DynamicCloudFrame();
                    frame.ImageFile = currentImageFile;
                    frame.Texture   = ImageHelper.LoadTexture(ddsFilePath);
                    CreateMesh(north, south, west, east, m_samples, currentImageFile, ref frame.Vertices, ref frame.Indices);

                    m_frames.Add(frame);
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
            }
        }
示例#48
0
 private void downloadDelegate_DidBegin(WebDownload download)
 {
     // add anything you want to do before the event is fired
 }
 public void didReceiveDataOfLength(WebDownload download, uint length)
 {
     DidReceiveDataOfLength(download, length);
 }
示例#50
0
        /// <summary>
        /// Downloads a back of a given media link. Also updates its size information so it can be loaded properly in the website.
        /// </summary>
        /// <param name="url"></param>
        public static void BackupAndUpdateSize(string url)
        {
            if (!Constants.DownloadData)
            return;
              // Use the last part of url to get a cleaner file name. May cause issues in the future but unlikely.
              var split = url.Split('/');
              var fileName = split[split.Length - 1];
              // Remove illegal characters to avoid problems with filesystems.
              fileName = fileName.Replace("\\", "").Replace("\"", "");
              if (Path.GetExtension(fileName).Equals(".gif"))
              {
            // Separate gifs based on source to get a nicer structure (no real advantage).
            if (url.Contains("gfycat"))
              fileName = Constants.BackupLocation + "gfycat\\" + fileName;
            else if(url.Contains("imgur"))
              fileName = Constants.BackupLocation + "imgur\\" + fileName;
            else
              fileName = Constants.BackupLocation + fileName;
              }
              else
            fileName = Constants.DataOtherRaw + Constants.LocalMediaFolder + CurrentDungeon + "\\" + fileName;
              // Function gets called for all kinds of links. Obviously all media files have a file extension.
              if (Path.GetExtension(fileName).Length == 0)
            return;
              if (downloadedFileNames.Contains(url))
            return;

              downloadedFileNames.Add(url);
              var dirName = Path.GetDirectoryName(fileName);
              if (dirName != null)
            Directory.CreateDirectory(dirName);
              // Don't download already existing files to make this much faster. This means that the backup must be deleted manually if content changes.
              if (!File.Exists(fileName))
              {
            // Use a custom timeout to make this work much faster.
            var timeOut = 10000;
            if (Path.GetExtension(fileName).Equals(".gif"))
              timeOut = 30000;
            using (var client = new WebDownload(timeOut))
            {
              var row = Console.CursorTop;
              try
              {
            Console.Write("Downloading " + url);
            client.DownloadFile(url, fileName);
            Helper.ClearConsoleLine(row);
              }
              catch (WebException)
              {
            Helper.ClearConsoleLine(row);
            ErrorHandler.ShowWarningMessage("File \"" + url + "\" can't be downloaded.");
              }
            }
              }
              if (!File.Exists(fileName))
            return;
              UpdateSizeInformation(fileName, url);
        }
示例#51
0
        /// <summary>
        /// 从网络上下载图片
        /// </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 caught)
            {
                System.Windows.Forms.MessageBox.Show(caught.ToString());
            }
            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;
                }
            }
        }