コード例 #1
0
        public string CheckJava(string binaryName)
        {
            var javapath = Path.Combine(RuntimeDirectory, "bin", binaryName);

            if (!File.Exists(javapath))
            {
                string json = "";

                var javaUrl = "";
                using (var wc = new WebClient())
                {
                    //this line was added
                    if (MRule.OSName == MRule.Linux)
                    {
                        return("java");
                    }

                    json = wc.DownloadString(MojangServer.LauncherMeta);

                    var job = JObject.Parse(json)[MRule.OSName];


                    javaUrl = job[MRule.Arch]?["jre"]?["url"]?.ToString();

                    if (string.IsNullOrEmpty(javaUrl))
                    {
                        throw new PlatformNotSupportedException("Downloading JRE on current OS is not supported. Set JavaPath manually.");
                    }

                    Directory.CreateDirectory(RuntimeDirectory);
                }

                var lzmapath = Path.Combine(Path.GetTempPath(), "jre.lzma");
                var zippath  = Path.Combine(Path.GetTempPath(), "jre.zip");

                var webdownloader = new WebDownload();
                webdownloader.DownloadProgressChangedEvent += Downloader_DownloadProgressChangedEvent;
                webdownloader.DownloadFile(javaUrl, lzmapath);

                DownloadCompleted?.Invoke(this, new EventArgs());

                SevenZipWrapper.DecompressFileLZMA(lzmapath, zippath);

                var z = new SharpZip(zippath);
                z.ProgressEvent += Z_ProgressEvent;
                z.Unzip(RuntimeDirectory);

                if (!File.Exists(javapath))
                {
                    throw new Exception("Failed Download");
                }

                if (MRule.OSName != MRule.Windows)
                {
                    IOUtil.Chmod(javapath, IOUtil.Chmod755);
                }
            }

            return(javapath);
        }
コード例 #2
0
ファイル: WMSModelNodes.cs プロジェクト: paladin74/Dapple
        protected override ModelNode[] Load()
        {
            WebDownload oCatalogDownload = new WebDownload(m_oUri.ToCapabilitiesUri(), true);

            oCatalogDownload.DownloadFile(CapabilitiesFilename);

            WMSList oCatalog = new WMSList(m_oUri.ToCapabilitiesUri(), CapabilitiesFilename);

            m_strTitle = oCatalog.Name;

            List <ModelNode> result = new List <ModelNode>();

            foreach (WMSLayer oLayer in oCatalog.Layers[0].ChildLayers)
            {
                if (oLayer.ChildLayers == null)
                {
                    result.Add(new WMSLayerModelNode(m_oModel, oLayer));
                }
                else
                {
                    result.Add(new WMSFolderModelNode(m_oModel, oLayer));
                }
            }
            if (oCatalog.Layers[0].Name != null)
            {
                result.Add(new WMSLayerModelNode(m_oModel, oCatalog.Layers[0]));
            }

            result.Sort(new Comparison <ModelNode>(WMSRootModelNode.SortWMSChildNodes));

            return(result.ToArray());
        }
コード例 #3
0
        public virtual void DownloadFiles(DownloadFile[] files)
        {
            var webdownload = new WebDownload();

            webdownload.DownloadProgressChangedEvent += fireDownloadProgressChangedEvent;

            var length = files.Length;

            if (length == 0)
            {
                return;
            }

            fireDownloadFileChangedEvent(files[0].Type, files[0].Name, length, 0);

            for (int i = 0; i < length; i++)
            {
                try
                {
                    var downloadFile = files[i];
                    Directory.CreateDirectory(Path.GetDirectoryName(downloadFile.Path));
                    webdownload.DownloadFile(downloadFile.Url, downloadFile.Path);
                    fireDownloadFileChangedEvent(downloadFile.Type, downloadFile.Name, length, i + 1);
                }
                catch (WebException ex)
                {
                    if (!IgnoreInvalidFiles)
                    {
                        throw new MDownloadFileException(ex.Message, ex, files[i]);
                    }
                }
            }
        }
コード例 #4
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;
                }
            }
        }
コード例 #5
0
ファイル: MJava.cs プロジェクト: CmlLib/CmlLib.Core
        private string downloadJavaLzma(string javaUrl)
        {
            Directory.CreateDirectory(RuntimeDirectory);
            string lzmapath = Path.Combine(Path.GetTempPath(), "jre.lzma");

            var webdownloader = new WebDownload();

            webdownloader.DownloadProgressChangedEvent += Downloader_DownloadProgressChangedEvent;
            webdownloader.DownloadFile(javaUrl, lzmapath);

            return(lzmapath);
        }
コード例 #6
0
        /// <summary>
        /// Install plugin from web (url).
        /// </summary>
        /// <param name="pluginUrl">http:// URL</param>
        void InstallFromUrl(Uri uri)
        {
            string fileName = Path.GetFileName(uri.LocalPath);
            string destPath = GetDestinationPath(fileName);

            if (destPath == null)
            {
                return;
            }

            using (WebDownload dl = new WebDownload(uri.ToString()))
                dl.DownloadFile(destPath);

            ShowSuccessMessage(fileName);
        }
コード例 #7
0
ファイル: PluginInstallDialog.cs プロジェクト: Fav/testww
        /// <summary>
        /// Install plugin from web (url).
        /// </summary>
        /// <param name="uri">http:// URL</param>
        void InstallFromUrl(Uri uri)
        {
            string fileName = Path.GetFileName(uri.LocalPath);
            string destPath = GetDestinationPath(fileName);

            if (destPath == null)
            {
                return;
            }
            // Offline mode check
            if (!World.Settings.WorkOffline)
            {
                using (WebDownload dl = new WebDownload(uri.ToString()))
                    dl.DownloadFile(destPath);

                ShowSuccessMessage(fileName);
            }
            else
            {
                MessageBox.Show("Offline mode active.", "Error");
            }
        }
コード例 #8
0
ファイル: MForge.cs プロジェクト: TURX/CmlLib.Core
        // legacy
        private void downloadUniversal(string mcversion, string forgeversion)
        {
            fireEvent(MFile.Library, "universal", 1, 0);

            var forgeName = $"forge-{mcversion}-{forgeversion}";
            var baseUrl   = $"{MavenServer}{mcversion}-{forgeversion}";

            var universalUrl  = $"{baseUrl}/{forgeName}-universal.jar";
            var universalPath = Path.Combine(
                Minecraft.Library,
                "net",
                "minecraftforge",
                "forge",
                $"{mcversion}-{forgeversion}",
                $"forge-{mcversion}-{forgeversion}.jar"
                );

            Directory.CreateDirectory(Path.GetDirectoryName(universalPath));
            var downloader = new WebDownload();

            downloader.DownloadFile(universalUrl, universalPath);
        }
コード例 #9
0
        public override void Initialize(DrawArgs drawArgs)
        {
            if (m_points == null)
            {
                Inited = true;
                return;
            }

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

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

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

                    m_texture = ImageHelper.LoadTexture(file.FullName);
                }
                else
                {
                    m_texture = ImageHelper.LoadTexture(m_imageUri);
                }
            }

            UpdateVertices();

            Inited = true;
        }
コード例 #10
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;
            }
        }
コード例 #11
0
        private void btnLoad_Click(object sender, EventArgs e)
        {
            if (tbFileName.Text == "")
            {
                return;
            }


            if (tbFileName.Text.EndsWith(".zip"))
            {
                //MessageBox.Show("Found zip");
                mainapp.InstallFromZip(tbFileName.Text);
                this.Close();
            }

            if (tbFileName.Text.Trim().StartsWith(@"http://"))
            {
                //MessageBox.Show("Found url");
                WebDownload dl       = new WebDownload(tbFileName.Text);
                string[]    urlList  = tbFileName.Text.Trim().Split('/');
                string      fileName = urlList[urlList.Length - 1];

                if (fileName.EndsWith(".xml"))
                {
                    //MessageBox.Show("Found web xml");
                    string dlPath = Path.Combine(MainApplication.Settings.ConfigPath, mainapp.WorldWindow.CurrentWorld.ToString());
                    dlPath = Path.Combine(dlPath, fileName);

                    try
                    {
                        dl.DownloadFile(dlPath);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Download error");
                        return;
                    }

                    mainapp.LoadAddon(dlPath);
                    this.Close();
                }
                else if (fileName.EndsWith(".cs"))
                {
                    //MessageBox.Show("Found web cs");
                    string dlPath = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), "//Plugins//");
                    dlPath = Path.Combine(dlPath, fileName);

                    try
                    {
                        dl.DownloadFile(dlPath);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Download error");
                        return;
                    }

                    MessageBox.Show("TODO: Load plugin here...");
                    this.Close();
                }
            }
            else
            {
                if (!File.Exists(tbFileName.Text))
                {
                    MessageBox.Show(tbFileName.Text + " does not exist", "Load error");
                    return;
                }

                FileInfo fi   = new FileInfo(tbFileName.Text);
                string   name = fi.Name;

                if (name.EndsWith(".xml"))
                {
                    //MessageBox.Show("Found local xml");
                    string dlPath = Path.Combine(MainApplication.Settings.ConfigPath, mainapp.WorldWindow.CurrentWorld.ToString());
                    dlPath = Path.Combine(dlPath, name);

                    if (!File.Exists(dlPath))
                    {
                        try
                        {
                            File.Copy(tbFileName.Text, dlPath);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Copy error");
                            return;
                        }
                    }

                    mainapp.LoadAddon(dlPath);
                    this.Close();
                }
                else if (tbFileName.Text.EndsWith(".cs"))
                {
                    //MessageBox.Show("Found local cs");
                    string dlPath = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), "//Plugins//");
                    dlPath = Path.Combine(dlPath, name);

                    if (!File.Exists(dlPath))
                    {
                        try
                        {
                            File.Copy(tbFileName.Text, dlPath);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Copy error");
                            return;
                        }
                    }

                    MessageBox.Show("TODO: Load plugin here...");
                    this.Close();
                }
            }
        }
コード例 #12
0
        /// <summary>
        /// 刷新图标集合图层
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void refreshTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (isUpdating)
            {
                return;
            }
            isUpdating = true;
            try
            {
                for (int i = 0; i < this.ChildObjects.Count; i++)
                {
                    RenderableObject ro = (RenderableObject)this.ChildObjects[i];
                    if (ro != null && ro.IsOn && ro is Icon)
                    {
                        Icon icon = (Icon)ro;

                        if (icon.RefreshInterval == TimeSpan.MaxValue || icon.LastRefresh > System.DateTime.Now - icon.RefreshInterval)
                        {
                            continue;
                        }

                        object      key         = null;
                        IconTexture iconTexture = null;

                        if (icon.TextureFileName != null && icon.TextureFileName.Length > 0)
                        {
                            if (icon.TextureFileName.ToLower().StartsWith("http://") && icon.SaveFilePath != null)
                            {
                                //download it
                                WebDownload webDownload = new WebDownload(icon.TextureFileName);
                                webDownload.DownloadType = DownloadType.Unspecified;

                                System.IO.FileInfo saveFile = new System.IO.FileInfo(icon.SaveFilePath);
                                if (!saveFile.Directory.Exists)
                                {
                                    saveFile.Directory.Create();
                                }

                                webDownload.DownloadFile(saveFile.FullName);

                                iconTexture = (IconTexture)m_textures[icon.SaveFilePath];
                                if (iconTexture != null)
                                {
                                    IconTexture tempTexture = iconTexture;
                                    m_textures[icon.SaveFilePath] = new IconTexture(DrawArgs.Device, icon.SaveFilePath);
                                    tempTexture.Dispose();
                                }
                                else
                                {
                                    key         = icon.SaveFilePath;
                                    iconTexture = new IconTexture(DrawArgs.Device, icon.SaveFilePath);

                                    // New texture, cache it
                                    m_textures.Add(key, iconTexture);

                                    // Use default dimensions if not set
                                    if (icon.Width == 0)
                                    {
                                        icon.Width = iconTexture.Width;
                                    }
                                    if (icon.Height == 0)
                                    {
                                        icon.Height = iconTexture.Height;
                                    }
                                }
                            }
                            else
                            {
                                // Icon image from file
                                iconTexture = (IconTexture)m_textures[icon.TextureFileName];
                                if (iconTexture != null)
                                {
                                    IconTexture tempTexture = iconTexture;
                                    m_textures[icon.SaveFilePath] = new IconTexture(DrawArgs.Device, icon.TextureFileName);
                                    tempTexture.Dispose();
                                }
                                else
                                {
                                    key         = icon.SaveFilePath;
                                    iconTexture = new IconTexture(DrawArgs.Device, icon.TextureFileName);

                                    // New texture, cache it
                                    m_textures.Add(key, iconTexture);

                                    // Use default dimensions if not set
                                    if (icon.Width == 0)
                                    {
                                        icon.Width = iconTexture.Width;
                                    }
                                    if (icon.Height == 0)
                                    {
                                        icon.Height = iconTexture.Height;
                                    }
                                }
                            }
                        }
                        else
                        {
                            // Icon image from bitmap
                            if (icon.Image != null)
                            {
                                iconTexture = (IconTexture)m_textures[icon.Image];
                                if (iconTexture != null)
                                {
                                    IconTexture tempTexture = iconTexture;
                                    m_textures[icon.SaveFilePath] = new IconTexture(DrawArgs.Device, icon.Image);
                                    tempTexture.Dispose();
                                }
                                else
                                {
                                    key         = icon.SaveFilePath;
                                    iconTexture = new IconTexture(DrawArgs.Device, icon.Image);

                                    // New texture, cache it
                                    m_textures.Add(key, iconTexture);

                                    // Use default dimensions if not set
                                    if (icon.Width == 0)
                                    {
                                        icon.Width = iconTexture.Width;
                                    }
                                    if (icon.Height == 0)
                                    {
                                        icon.Height = iconTexture.Height;
                                    }
                                }
                            }
                        }

                        icon.LastRefresh = System.DateTime.Now;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                isUpdating = false;
            }
        }
コード例 #13
0
ファイル: ModelFeature.cs プロジェクト: jooo000hn/MFW3DNet
        /// <summary>
        /// RenderableObject abstract member (needed)
        /// OBS: Worker thread (don't update UI directly from this thread)
        /// </summary>
        public override void Initialize(DrawArgs drawArgs)
        {
            if (!IsVisible(drawArgs.WorldCamera))
            {
                return;
            }
            if (meshFileName.StartsWith("http"))
            {
                Uri    meshuri   = new Uri(meshFileName);
                string meshpath  = meshuri.AbsolutePath;
                string extension = Path.GetExtension(meshpath);
                //download online mesh files to cache and
                //update meshfilename to new name
                if (meshuri.Scheme == Uri.UriSchemeHttp ||
                    meshuri.Scheme == Uri.UriSchemeHttps)
                {
                    try
                    {
                        // Offline check
                        if (World.Settings.WorkOffline)
                        {
                            throw new Exception("Offline mode active.");
                        }

                        WebDownload request = new WebDownload(meshFileName);

                        string cachefilename = request.GetHashCode() + extension;
                        //HACK: Hard Coded Path
                        cachefilename =
                            Directory.GetParent(System.Windows.Forms.Application.ExecutablePath) +
                            "//Cache//Models//" + cachefilename;
                        if (!File.Exists(cachefilename))
                        {
                            request.DownloadFile(cachefilename);
                        }
                        meshFileName = cachefilename;
                    }
                    catch (Exception caught)
                    {
                        Utility.Log.Write(caught);
                        errorMsg = "Failed to download mesh from " + meshFileName;
                    }
                }
            }
            string ext = Path.GetExtension(meshFileName);

            try
            {
                lock (m_thisLock)
                {
                    if (m_meshTable.ContainsKey(meshFileName))
                    {
                        m_meshTableElem = m_meshTable[meshFileName];
                        m_meshTableElem.referenceCount++;
                        m_meshElems = m_meshTableElem.meshElems;
                    }
                    else
                    {
                        if (ext.Equals(".x"))
                        {
                            LoadDirectXMesh(drawArgs);
                        }
                        else if (ext.Equals(".dae") || ext.Equals(".xml"))
                        {
                            LoadColladaMesh(drawArgs);
                        }

                        // if mesh loaded then add to the mesh table
                        if (m_meshElems != null)
                        {
                            m_meshTableElem = new MeshTableElem();
                            m_meshTableElem.meshFilePath   = meshFileName;
                            m_meshTableElem.meshElems      = m_meshElems;
                            m_meshTableElem.referenceCount = 1;

                            m_meshTable.Add(meshFileName, m_meshTableElem);
                        }
                    }
                }

                if (m_meshElems == null)
                {
                    throw new InvalidMeshException();
                }

                //vertExaggeration = World.Settings.VerticalExaggeration;
                //if (m_isElevationRelativeToGround == true)
                //    currentElevation = World.TerrainAccessor.GetElevationAt(Latitude, Longitude);

                if (refreshTimer == null && m_refreshurl != null)
                {
                    refreshTimer          = new System.Timers.Timer(60000);
                    refreshTimer.Elapsed += new System.Timers.ElapsedEventHandler(refreshTimer_Elapsed);
                    refreshTimer.Start();
                }

                isInitialized = true;
            }
            catch (Exception caught)
            {
                Utility.Log.Write(caught);
                errorMsg = "Failed to read mesh from " + meshFileName;
            }
        }
コード例 #14
0
        /// <summary>
        /// Downloads a KML/KMZ file from the given URL
        /// </summary>
        private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (bUpdating)
            {
                return;
            }
            bUpdating = true;

            try
            {
                if (!m_firedStartup || (layer != null && layer.IsOn))
                {
                    string fullurl = url;
                    if (sender == viewTimer)
                    {
                        if (!bViewStopped)
                        {
                            if (DrawArgs.Camera.ViewMatrix != lastView)
                            {
                                lastView  = DrawArgs.Camera.ViewMatrix;
                                bUpdating = false;
                                return;
                            }
                            bViewStopped = true;
                        }
                        else
                        {
                            if (DrawArgs.Camera.ViewMatrix != lastView)
                            {
                                lastView     = DrawArgs.Camera.ViewMatrix;
                                bViewStopped = false;
                            }
                            bUpdating = false;
                            return;
                        }
                        fullurl += (fullurl.IndexOf('?') == -1 ? "?" : "&") + GetBBox();
                    }

                    string saveFile = Path.GetFileName(Uri.EscapeDataString(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
                            owner.ReadKML(kml, 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);
                        }
                    }
                    m_firedStartup = true;
                }
            }
            catch (Exception ex)
            {
                Log.Write(Log.Levels.Error, "KMLParser: " + ex.ToString());
            }

            bUpdating = false;
        }
コード例 #15
0
ファイル: MainForm.cs プロジェクト: zdomokos/OptionsOracle
        private bool backgroundWorker_DoPartialUpgrade(object sender, DoWorkEventArgs e, string path, string host, List <string> update, List <string> remove)
        {
            BackgroundWorker bw = (BackgroundWorker)sender;

            try
            {
                LogWrite("Performing partial upgrade...");

                if (remove != null)
                {
                    LogWrite("Removing obsolete files...");

                    foreach (string file in remove)
                    {
                        string final_file = System.IO.Path.Combine(path, file);

                        LogWrite("Removing " + file + " ...");

                        if (System.IO.File.Exists(final_file))
                        {
                            System.IO.File.Delete(final_file);
                        }
                    }
                }

                if (update != null)
                {
                    LogWrite("Upgrading new files...");

                    foreach (string file in update)
                    {
                        string remote_file = host + "/" + file;
                        string local_file  = System.IO.Path.GetTempPath() + System.IO.Path.GetFileName(file);
                        string final_file  = System.IO.Path.Combine(path, file);

                        // remove file if exist
                        if (System.IO.File.Exists(local_file))
                        {
                            System.IO.File.Delete(local_file);
                        }

                        LogWrite("Downloading " + file + " ...");

                        WebDownload web = new WebDownload(bw);
                        Exception   ex  = web.DownloadFile(remote_file, local_file);

                        if (ex != null)
                        {
                            LogWrite("Download failed!");
                            e.Result = "Failed";
                            throw ex;
                        }

                        LogWrite("Copying " + file + " ...");

                        // copy downloaded file to program directory
                        File.Copy(local_file, final_file, true);

                        LogWrite("File " + file + " upgrade completed.");
                    }
                }

                LogWrite("Partial upgrade installation completed.");

                e.Result = "OK";
            }
            catch (Exception ex)
            {
                LogWrite("Partial upgrade failed! (" + ex.Message + ");Full upgrade installation failed!");
                e.Result = "Failed";
                return(false);
            }

            return(true);
        }
コード例 #16
0
ファイル: MainForm.cs プロジェクト: zdomokos/OptionsOracle
        private bool backgroundWorker_DoFullUpgrade(object sender, DoWorkEventArgs e, string host, string file)
        {
            BackgroundWorker bw = (BackgroundWorker)sender;

            try
            {
                LogWrite("Performing full upgrade.");

                string remote_file = host + "/" + file;
                string local_file  = System.IO.Path.GetTempPath() + System.IO.Path.GetFileName(file);

                // remove file if exist
                if (System.IO.File.Exists(local_file))
                {
                    System.IO.File.Delete(local_file);
                }

                LogWrite("Downloading OptionsOracle installation file...");

                WebDownload web = new WebDownload(bw);
                Exception   ex  = web.DownloadFile(remote_file, local_file);

                if (ex != null)
                {
                    LogWrite("Download failed!");
                    e.Result = "Failed";
                    throw ex;
                }

                LogWrite("Download completed. Starting installation...");

                // start installation process

                ProcessRun pro       = new ProcessRun();
                int        exit_code = pro.RunProcess(local_file);

                if (exit_code == 0)
                {
                    LogWrite("Full upgrade installation completed.");

                    e.Result = "OK";
                }
                else if (exit_code == 1602)
                {
                    LogWrite("Full upgrade installation aborted!");
                    e.Result = "Failed";
                }
                else
                {
                    LogWrite("Full upgrade installation failed!");
                    e.Result = "Failed";
                }
            }
            catch (Exception ex)
            {
                LogWrite("Full upgrade installation failed! (" + ex.Message + ");Full upgrade installation failed!");
                e.Result = "Failed";
                return(false);
            }

            return(true);
        }
コード例 #17
0
        public override void Initialize(DrawArgs drawArgs)
        {
            if (!isOn)
            {
                return;
            }

            if (m_sprite != null)
            {
                m_sprite.Dispose();
                m_sprite = null;
            }

            m_sprite = new Sprite(drawArgs.Device);

            TimeSpan smallestRefreshInterval = TimeSpan.MaxValue;

            // Load all textures
            foreach (RenderableObject ro in m_children)
            {
                Icon icon = ro as Icon;
                if (icon == null)
                {
                    // Child is not an icon
                    if (ro.IsOn)
                    {
                        ro.Initialize(drawArgs);
                    }
                    continue;
                }

                if (icon.RefreshInterval.TotalMilliseconds != 0 && icon.RefreshInterval != TimeSpan.MaxValue &&
                    icon.RefreshInterval < smallestRefreshInterval)
                {
                    smallestRefreshInterval = icon.RefreshInterval;
                }

                // Child is an icon
                icon.Initialize(drawArgs);

                object      key         = null;
                IconTexture iconTexture = null;

                if (icon.TextureFileName != null &&
                    icon.TextureFileName.Length > 0)
                {
                    if (icon.TextureFileName.ToLower().StartsWith("http://") &&
                        icon.SaveFilePath != null)
                    {
                        //download it
                        try {
                            WebDownload webDownload = new WebDownload(icon.TextureFileName);
                            webDownload.DownloadType = DownloadType.Unspecified;

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

                            webDownload.DownloadFile(saveFile.FullName);
                        }
                        catch {}

                        iconTexture = (IconTexture)m_textures[icon.SaveFilePath];
                        if (iconTexture == null)
                        {
                            key         = icon.SaveFilePath;
                            iconTexture = new IconTexture(drawArgs.Device, icon.SaveFilePath);
                        }
                    }
                    else
                    {
                        // Icon image from file
                        iconTexture = (IconTexture)m_textures[icon.TextureFileName];
                        if (iconTexture == null)
                        {
                            key         = icon.TextureFileName;
                            iconTexture = new IconTexture(drawArgs.Device, icon.TextureFileName);
                        }
                    }
                }
                else
                {
                    // Icon image from bitmap
                    if (icon.Image != null)
                    {
                        iconTexture = (IconTexture)m_textures[icon.Image];
                        if (iconTexture == null)
                        {
                            // Create new texture from image
                            key         = icon.Image;
                            iconTexture = new IconTexture(drawArgs.Device, icon.Image);
                        }
                    }
                }

                if (iconTexture == null)
                {
                    // No texture set
                    continue;
                }

                if (key != null)
                {
                    // New texture, cache it
                    m_textures.Add(key, iconTexture);

                    // Use default dimensions if not set
                    if (icon.Width == 0)
                    {
                        icon.Width = iconTexture.Width;
                    }
                    if (icon.Height == 0)
                    {
                        icon.Height = iconTexture.Height;
                    }
                }
            }

            // Compute mouse over bounding boxes
            foreach (RenderableObject ro in m_children)
            {
                Icon icon = ro as Icon;
                if (icon == null)
                {
                    // Child is not an icon
                    continue;
                }

                if (GetTexture(icon) == null)
                {
                    // Label only
                    icon.SelectionRectangle = drawArgs.DefaultDrawingFont.MeasureString(null, icon.Name, DrawTextFormat.None, 0);
                }
                else
                {
                    // Icon only
                    icon.SelectionRectangle = new Rectangle(0, 0, icon.Width, icon.Height);
                }

                // Center the box at (0,0)
                icon.SelectionRectangle.Offset(-icon.SelectionRectangle.Width / 2, -icon.SelectionRectangle.Height / 2);
            }

            if (refreshTimer == null &&
                smallestRefreshInterval != TimeSpan.MaxValue)
            {
                refreshTimer          = new Timer(smallestRefreshInterval.TotalMilliseconds);
                refreshTimer.Elapsed += new ElapsedEventHandler(refreshTimer_Elapsed);
                refreshTimer.Start();
            }

            Inited = true;
        }
コード例 #18
0
ファイル: PictureBox.cs プロジェクト: sigswj/WorldWind
        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();
            }
        }
コード例 #19
0
ファイル: LinkGenerator.cs プロジェクト: Wethospu/gw2dungeons
        /// <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);
        }
コード例 #20
0
ファイル: DynamicCloudLayer.cs プロジェクト: Fav/testww
        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);
            }
        }